@revoengine/cli 2.1.1 → 2.2.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 (64) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +111 -12
  3. package/dist/src/application-access.d.ts +4 -0
  4. package/dist/src/application-access.js +18 -0
  5. package/dist/src/application-cors.d.ts +2 -0
  6. package/dist/src/application-cors.js +19 -0
  7. package/dist/src/argument-contract.js +24 -4
  8. package/dist/src/automation-contract.generated.d.ts +165 -6
  9. package/dist/src/automation-contract.generated.js +198 -6
  10. package/dist/src/cli.js +10 -2
  11. package/dist/src/client.d.ts +53 -1
  12. package/dist/src/client.js +84 -0
  13. package/dist/src/commands/applications.d.ts +2 -0
  14. package/dist/src/commands/applications.js +44 -0
  15. package/dist/src/commands/emulate.d.ts +1 -0
  16. package/dist/src/commands/emulate.js +79 -3
  17. package/dist/src/commands/index.d.ts +2 -0
  18. package/dist/src/commands/index.js +2 -0
  19. package/dist/src/commands/migrate.js +10 -2
  20. package/dist/src/commands/sites.d.ts +2 -0
  21. package/dist/src/commands/sites.js +156 -0
  22. package/dist/src/component-lock.d.ts +2 -1
  23. package/dist/src/component-lock.js +22 -1
  24. package/dist/src/endpoint-application.d.ts +25 -0
  25. package/dist/src/endpoint-application.js +75 -0
  26. package/dist/src/endpoint-emulator.d.ts +5 -0
  27. package/dist/src/endpoint-emulator.js +29 -0
  28. package/dist/src/endpoint-storage-transports.d.ts +2 -0
  29. package/dist/src/endpoint-storage-transports.js +8 -0
  30. package/dist/src/metadata-backfill.d.ts +1 -1
  31. package/dist/src/metadata-backfill.js +10 -1
  32. package/dist/src/migration.d.ts +6 -2
  33. package/dist/src/migration.js +104 -41
  34. package/dist/src/project.d.ts +8 -1
  35. package/dist/src/project.js +4 -0
  36. package/dist/src/request-contract.d.ts +5 -0
  37. package/dist/src/request-contract.js +12 -0
  38. package/dist/src/resource-inventory.d.ts +4 -2
  39. package/dist/src/resource-inventory.js +16 -1
  40. package/dist/src/resource-syncs/account-principal.d.ts +2 -0
  41. package/dist/src/resource-syncs/account-principal.js +3 -0
  42. package/dist/src/resource-syncs/application-principals.d.ts +60 -0
  43. package/dist/src/resource-syncs/application-principals.js +151 -0
  44. package/dist/src/resource-syncs/application-sync.d.ts +110 -0
  45. package/dist/src/resource-syncs/application-sync.js +328 -0
  46. package/dist/src/resource-syncs/endpoint-sync.d.ts +38 -0
  47. package/dist/src/resource-syncs/endpoint-sync.js +278 -14
  48. package/dist/src/resource-syncs/group-sync.d.ts +12 -0
  49. package/dist/src/resource-syncs/group-sync.js +60 -6
  50. package/dist/src/resource-syncs/runtime-definition-validation.js +26 -1
  51. package/dist/src/resource-syncs/service-account-sync.d.ts +10 -0
  52. package/dist/src/resource-syncs/service-account-sync.js +32 -4
  53. package/dist/src/reviewed-plan.js +2 -2
  54. package/dist/src/sync-omit-write-fence.js +4 -1
  55. package/dist/src/sync-omit.d.ts +1 -1
  56. package/dist/src/sync-omit.js +7 -2
  57. package/dist/src/tracked-resources.d.ts +1 -1
  58. package/dist/src/tracked-resources.js +3 -2
  59. package/dist/src/types.d.ts +30 -0
  60. package/dist/src/ui.js +2 -0
  61. package/dist/src/workspace-diff.js +1 -0
  62. package/dist/src/workspace-digests.js +2 -0
  63. package/dist/src/workspace-prune.js +67 -9
  64. package/package.json +2 -2
@@ -0,0 +1,151 @@
1
+ import { groupRevisionHash } from "./group-sync.js";
2
+ import { mapWithConcurrency } from "../utils.js";
3
+ import { HTTP_REQUEST_CONCURRENCY } from "../request-queue.js";
4
+ import { readConfiguredResourceMetadataStableKey } from "../resource-metadata.js";
5
+ import { APPLICATION_UUID, validApplicationInvocationPolicy } from "../application-access.js";
6
+ import { accountPrincipal, resolveSystemAccount, serviceAccountRevisionHash, validExecutionPrincipal } from "./account-principal.js";
7
+ import { isRecord, unwrapData } from "./util.js";
8
+ import { readProjectMetadata } from "../project.js";
9
+ import { resolveAuthenticatedInstance } from "../resource-target.js";
10
+ import { hashStable } from "../component-lock.js";
11
+ export function validPortableApplicationInvocationPolicy(value) {
12
+ if (!isRecord(value) || Object.keys(value).some(key => !['mode', 'users', 'serviceAccounts', 'groups'].includes(key)) || !['all', 'allowlist', 'denylist'].includes(String(value.mode))
13
+ || !Array.isArray(value.users) || !Array.isArray(value.serviceAccounts) || value.users.length > 500 || value.serviceAccounts.length > 500)
14
+ return false;
15
+ if (value.users.some(user => !isRecord(user) || Object.keys(user).length !== 2 || typeof user.instanceId !== 'string' || !APPLICATION_UUID.test(user.instanceId) || typeof user.userId !== 'string' || !APPLICATION_UUID.test(user.userId))
16
+ || value.serviceAccounts.some(principal => !validExecutionPrincipal(principal)))
17
+ return false;
18
+ if (value.groups !== undefined && (!Array.isArray(value.groups) || value.groups.length > 500 || value.groups.some(group => !isRecord(group) || group.type !== 'group' || typeof group.stableKey !== 'string' || !group.stableKey.trim() || Object.keys(group).some(key => !['type', 'stableKey'].includes(key))) || new Set(value.groups.map(group => group.stableKey)).size !== value.groups.length))
19
+ return false;
20
+ return new Set(value.users.map(user => `${user.instanceId.toLowerCase()}:${user.userId.toLowerCase()}`)).size === value.users.length
21
+ && new Set(value.serviceAccounts.map(principal => hashStable(principal))).size === value.serviceAccounts.length
22
+ && (value.mode !== 'all' || value.users.length + value.serviceAccounts.length === 0 && !value.groups?.length);
23
+ }
24
+ export function applicationUserMappings(cwd, envName) {
25
+ const configured = readProjectMetadata(cwd)?.applicationUserMappings;
26
+ if (configured === undefined)
27
+ return [];
28
+ if (!isRecord(configured))
29
+ throw new Error('applicationUserMappings must be an environment-keyed object.');
30
+ const entries = Object.hasOwn(configured, envName) ? configured[envName] : [];
31
+ if (!Array.isArray(entries))
32
+ throw new Error(`applicationUserMappings[${envName}] must be an array.`);
33
+ const seen = new Set();
34
+ for (const entry of entries) {
35
+ if (!isRecord(entry) || Object.keys(entry).length !== 3 || !['sourceInstanceId', 'sourceUserId', 'targetUserId'].every(key => typeof entry[key] === 'string' && APPLICATION_UUID.test(entry[key])))
36
+ throw new Error('Application user mappings require exactly sourceInstanceId/sourceUserId/targetUserId UUIDs.');
37
+ const key = `${entry.sourceInstanceId.toLowerCase()}:${entry.sourceUserId.toLowerCase()}`;
38
+ if (seen.has(key))
39
+ throw new Error('Application user mapping is ambiguous; each source identity requires exactly one target.');
40
+ seen.add(key);
41
+ }
42
+ return entries;
43
+ }
44
+ async function human(client, id, requireActive = false) {
45
+ const account = await client.getAccount(id);
46
+ if (account.userId?.toLowerCase() !== id.toLowerCase() || account.serviceAccount !== false || account.deletedAt || account.deletedBy || requireActive && (![0, 'ACTIVE'].includes(account.status) || account.metadata?.__serviceAccountSync))
47
+ throw new Error(`Application user ${id} must resolve to a current human account on the selected target.`);
48
+ return account;
49
+ }
50
+ export async function portableApplicationInvocationPolicy(client, policy, stableKeyName) {
51
+ if (!validApplicationInvocationPolicy(policy))
52
+ throw new Error('Invalid remote Application invocation policy.');
53
+ const instanceId = policy.users.length ? await resolveAuthenticatedInstance(client, 'source') : '';
54
+ const users = await mapWithConcurrency(policy.users, async (userId) => { await human(client, userId); return { instanceId, userId }; }, HTTP_REQUEST_CONCURRENCY);
55
+ const serviceAccounts = await mapWithConcurrency(policy.serviceAccounts, async (id) => {
56
+ const principal = await accountPrincipal(client, id, stableKeyName);
57
+ if (!principal)
58
+ throw new Error(`Application Service Account ${id} has no unambiguous portable Stable Key.`);
59
+ return principal;
60
+ }, HTTP_REQUEST_CONCURRENCY);
61
+ const groups = policy.groups === undefined ? undefined : await mapWithConcurrency(policy.groups, async (groupId) => {
62
+ const group = unwrapData(await client.getGroup(groupId));
63
+ const stableKey = readConfiguredResourceMetadataStableKey(group, stableKeyName);
64
+ if (group.groupId?.toLowerCase() !== groupId.toLowerCase() || group.deletedAt || group.deletedBy || !stableKey)
65
+ throw new Error('Application Group requires a live source identity and portable Stable Key.');
66
+ return { type: 'group', stableKey };
67
+ }, HTTP_REQUEST_CONCURRENCY);
68
+ return { mode: policy.mode, users, serviceAccounts, ...(groups === undefined ? {} : { groups }) };
69
+ }
70
+ export async function resolveApplicationInvocationPolicy(input, policy) {
71
+ const mappings = applicationUserMappings(input.cwd, input.envName);
72
+ const instanceId = policy.users.length ? await resolveAuthenticatedInstance(input.client, 'target') : '';
73
+ const users = await mapWithConcurrency(policy.users, async (reference) => {
74
+ const mapping = mappings.find(entry => entry.sourceInstanceId.toLowerCase() === reference.instanceId.toLowerCase() && entry.sourceUserId.toLowerCase() === reference.userId.toLowerCase());
75
+ const id = mapping?.targetUserId ?? (reference.instanceId.toLowerCase() === instanceId.toLowerCase() ? reference.userId : undefined);
76
+ if (!id)
77
+ throw new Error(`Application user ${reference.instanceId}/${reference.userId} requires an explicit applicationUserMappings[${input.envName}] entry for this target; users are never matched by email.`);
78
+ await human(input.client, id, true);
79
+ return id;
80
+ }, HTTP_REQUEST_CONCURRENCY);
81
+ const serviceAccounts = (await policyServiceAccounts(input, policy.serviceAccounts)).map(binding => binding.account.userId);
82
+ const groups = policy.groups === undefined ? undefined : (await policyGroups(input, policy.groups)).map(binding => binding.group.groupId);
83
+ const resolved = { mode: policy.mode, users, serviceAccounts, ...(groups === undefined ? {} : { groups }) };
84
+ if (!validApplicationInvocationPolicy(resolved))
85
+ throw new Error('Application principal mappings collapse or conflict on the target.');
86
+ return resolved;
87
+ }
88
+ /** A planned new SA is validated by the identity stage before Application upsert. */
89
+ export async function canonicalApplicationInvocationPolicy(input, policy) {
90
+ const usersOnly = await resolveApplicationInvocationPolicy(input, { ...policy, serviceAccounts: [], groups: undefined });
91
+ await policyServiceAccounts(input, policy.serviceAccounts);
92
+ if (policy.groups !== undefined)
93
+ await policyGroups(input, policy.groups);
94
+ return { mode: policy.mode, users: usersOnly.users.map(userId => ({ instanceId: input.client.instance, userId })), serviceAccounts: policy.serviceAccounts, ...(policy.groups === undefined ? {} : { groups: policy.groups }) };
95
+ }
96
+ async function policyServiceAccounts(input, principals) {
97
+ // Resolve the catalog once per policy; a 500-principal ACL must not cause 500 full account inventories.
98
+ const byKey = new Map();
99
+ if (principals.some(principal => principal.kind === 'service-account')) {
100
+ const { serviceAccounts } = await input.client.listAllServiceAccounts();
101
+ const accounts = await mapWithConcurrency(serviceAccounts, summary => input.client.getServiceAccount(String(summary.userId)), HTTP_REQUEST_CONCURRENCY);
102
+ for (const account of accounts) {
103
+ const key = readConfiguredResourceMetadataStableKey(account, input.stableKeyName ?? 'stableKey');
104
+ if (key && account.userId !== '00000000-0000-0000-0000-000000000000')
105
+ byKey.set(key, [...(byKey.get(key) ?? []), account]);
106
+ }
107
+ }
108
+ return mapWithConcurrency(principals, async (principal) => {
109
+ const matches = principal.kind === 'system' ? [await resolveSystemAccount(input.client, true)] : byKey.get(principal.stableKey) ?? [];
110
+ if (matches.length === 0 && principal.kind === 'service-account' && input.projectedServiceAccounts?.includes(principal.stableKey))
111
+ return { principal };
112
+ if (matches.length !== 1)
113
+ throw new Error('Application Service Account must resolve uniquely on target or be included in the reviewed identity stage.');
114
+ const account = matches[0];
115
+ if (!account.userId || account.serviceAccount !== true || ![0, 'ACTIVE'].includes(account.status) || account.deletedAt || account.deletedBy || account.metadata?.__serviceAccountSync)
116
+ throw new Error('Application invocation policy requires active, type-correct target Service Accounts.');
117
+ return { principal, account };
118
+ }, HTTP_REQUEST_CONCURRENCY);
119
+ }
120
+ export async function applicationPrincipalFences(input, policy) {
121
+ return (await policyServiceAccounts(input, policy?.serviceAccounts ?? [])).map(({ principal, account }) => ({ principal, ...(account ? { userId: account.userId, revisionHash: serviceAccountRevisionHash(account) } : {}) }));
122
+ }
123
+ export async function applicationHumanFences(client, policy) {
124
+ return mapWithConcurrency(policy?.users ?? [], async (reference) => {
125
+ const account = await human(client, reference.userId);
126
+ return { userId: reference.userId, revisionHash: hashStable({ userId: account.userId, version: account.version, status: account.status, serviceAccount: account.serviceAccount }) };
127
+ }, HTTP_REQUEST_CONCURRENCY);
128
+ }
129
+ async function policyGroups(input, references) {
130
+ if (!references.length)
131
+ return [];
132
+ const { groups } = await input.client.listAllGroups();
133
+ const records = await mapWithConcurrency(groups, async (summary) => unwrapData(await input.client.getGroup(String(summary.groupId || summary.id))), HTTP_REQUEST_CONCURRENCY);
134
+ const byKey = new Map();
135
+ for (const group of records) {
136
+ const key = readConfiguredResourceMetadataStableKey(group, input.stableKeyName ?? 'stableKey');
137
+ if (key)
138
+ byKey.set(key, [...(byKey.get(key) ?? []), group]);
139
+ }
140
+ return references.map(reference => {
141
+ const matches = byKey.get(reference.stableKey) ?? [];
142
+ if (!matches.length && input.projectedGroups?.includes(reference.stableKey))
143
+ return { reference };
144
+ if (matches.length !== 1 || !matches[0].groupId || matches[0].deletedAt || matches[0].deletedBy)
145
+ throw new Error('Application Group must resolve to one live target Group or a reviewed identity-stage create.');
146
+ return { reference, group: matches[0] };
147
+ });
148
+ }
149
+ export async function applicationGroupFences(input, policy) {
150
+ return (await policyGroups(input, policy?.groups ?? [])).map(({ reference, group }) => ({ reference, ...(group ? { groupId: group.groupId, revisionHash: groupRevisionHash(group) } : {}) }));
151
+ }
@@ -0,0 +1,110 @@
1
+ import type { VerifiedGroup } from './group-sync.ts';
2
+ import type { VerifiedServiceAccount } from './service-account-sync.ts';
3
+ import { type ApplicationGroupFence, type ApplicationPrincipalFence, type PortableApplicationInvocationPolicy } from './application-principals.ts';
4
+ export { validApplicationCors } from '../application-cors.ts';
5
+ import type { RevoClient } from '../client.ts';
6
+ import type { ApplicationAnonymousAccess, ApplicationCors, ApplicationRecord } from '../types.ts';
7
+ export type ApplicationManifest = {
8
+ kind: 'application';
9
+ key: string;
10
+ name?: string;
11
+ description?: string | null;
12
+ cors: ApplicationCors;
13
+ invocationPolicy?: PortableApplicationInvocationPolicy | null;
14
+ anonymousAccess?: ApplicationAnonymousAccess | null;
15
+ };
16
+ export type ApplicationPlanItem = {
17
+ stableKey: string;
18
+ name: string;
19
+ status: 'create' | 'clean' | 'safe-update' | 'remote-changed' | 'conflict' | 'missing-lock' | 'orphan' | 'skipped';
20
+ desiredHash?: string;
21
+ currentHash?: string;
22
+ baselineHash?: string;
23
+ targetRevisionHash?: string;
24
+ mappingHash?: string;
25
+ groupFences?: ApplicationGroupFence[];
26
+ principalFences?: ApplicationPrincipalFence[];
27
+ humanFences?: Array<{
28
+ userId: string;
29
+ revisionHash: string;
30
+ }>;
31
+ reason?: string;
32
+ changedFields?: string[];
33
+ };
34
+ export type ApplicationsPlan = {
35
+ resourceType: 'application';
36
+ env: string;
37
+ counts: Record<ApplicationPlanItem['status'], number>;
38
+ items: ApplicationPlanItem[];
39
+ blockers: string[];
40
+ warnings: string[];
41
+ exclusions: string[];
42
+ };
43
+ export type ApplicationPullResult = {
44
+ pulled: {
45
+ manifest: ApplicationManifest;
46
+ targetPath: string;
47
+ }[];
48
+ pruned: {
49
+ stableKey: string;
50
+ targetPath: string;
51
+ }[];
52
+ skipped: {
53
+ targetPath: string;
54
+ reason: string;
55
+ }[];
56
+ };
57
+ export type VerifiedApplication = {
58
+ key: string;
59
+ serviceId: string;
60
+ version: number;
61
+ desiredHash: string;
62
+ revisionHash: string;
63
+ };
64
+ export type ApplicationPushResult = {
65
+ stableKey: string;
66
+ action: 'create' | 'update' | 'noop' | 'orphan' | 'skipped';
67
+ status: 'deployed' | 'failed' | 'skipped';
68
+ targetPath: string;
69
+ reason?: string;
70
+ error?: string;
71
+ verifiedApplication?: VerifiedApplication;
72
+ };
73
+ type Input = {
74
+ client: RevoClient;
75
+ cwd: string;
76
+ envName: string;
77
+ stableKeyName?: string;
78
+ projectedServiceAccounts?: string[];
79
+ verifiedServiceAccounts?: VerifiedServiceAccount[];
80
+ projectedGroups?: string[];
81
+ verifiedGroups?: VerifiedGroup[];
82
+ };
83
+ export declare function applicationApiUnavailable(error: unknown): boolean;
84
+ export declare function validApplicationKey(value: unknown): value is string;
85
+ export declare function validateApplicationManifest(value: unknown): value is ApplicationManifest;
86
+ export declare function applicationItemAction(item: ApplicationPlanItem): 'create' | 'update' | 'adopt' | 'noop' | 'excluded' | 'blocked';
87
+ export declare function applicationManifestFromRecord(record: ApplicationRecord, client?: RevoClient, stableKeyName?: string): Promise<ApplicationManifest>;
88
+ export declare function hashPortableApplication(manifest: ApplicationManifest): string;
89
+ export declare function applicationRevisionHash(record: ApplicationRecord): string;
90
+ export declare function loadRemoteApplications(client: RevoClient): Promise<ApplicationRecord[]>;
91
+ export declare function readWorkspaceApplications(cwd: string): {
92
+ manifest: ApplicationManifest;
93
+ manifestPath: string;
94
+ }[];
95
+ export declare function pullApplicationsToWorkspace(input: Input & {
96
+ force?: boolean;
97
+ pruneOrphans?: boolean;
98
+ allowUnsupported?: boolean;
99
+ }): Promise<ApplicationPullResult>;
100
+ export declare function buildApplicationsPlan(input: Input & {
101
+ allowUnsupported?: boolean;
102
+ }): Promise<ApplicationsPlan>;
103
+ export declare function pushApplications(input: Input & {
104
+ force?: boolean;
105
+ allowUnsupported?: boolean;
106
+ reviewedPlan?: ApplicationsPlan;
107
+ }): Promise<{
108
+ plan: ApplicationsPlan;
109
+ results: ApplicationPushResult[];
110
+ }>;
@@ -0,0 +1,328 @@
1
+ import { validApplicationAnonymousAccess, validApplicationInvocationPolicy } from "../application-access.js";
2
+ import { applicationGroupFences, applicationHumanFences, applicationPrincipalFences, canonicalApplicationInvocationPolicy, applicationUserMappings, portableApplicationInvocationPolicy, resolveApplicationInvocationPolicy, validPortableApplicationInvocationPolicy } from "./application-principals.js";
3
+ import { validApplicationCors } from "../application-cors.js";
4
+ export { validApplicationCors } from "../application-cors.js";
5
+ import path from 'node:path';
6
+ import { ApiError } from "../client.js";
7
+ import { DEFAULT_ENDPOINT_APPLICATION_ID } from "../endpoint-application.js";
8
+ import { validateRequestContract } from "../request-contract.js";
9
+ import { hashStable, readComponentLock, writeComponentLock } from "../component-lock.js";
10
+ import { assertOmittedPropertiesPreserved, hashSyncDefinition, preserveOmittedProperties, syncSourceBaselineHash, syncBaselineHash, omitPaths, withoutSyncOmit } from "../sync-omit.js";
11
+ import { readJsonFile } from "../utils.js";
12
+ import { findManifestFiles, isRecord, localTargetPath, removeRelocatedManifest, requireProjectLayout, toPortableRelativePath, writePulledManifest } from "./util.js";
13
+ const statuses = ['create', 'clean', 'safe-update', 'remote-changed', 'conflict', 'missing-lock', 'orphan', 'skipped'];
14
+ export function applicationApiUnavailable(error) {
15
+ return error instanceof ApiError && error.status === 404;
16
+ }
17
+ export function validApplicationKey(value) {
18
+ return typeof value === 'string' && (value === '@default' || value !== 'default' && /^(?=.{1,63}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?![\s\S])/.test(value));
19
+ }
20
+ export function validateApplicationManifest(value) {
21
+ if (!isRecord(value) || value.kind !== 'application' || !validApplicationKey(value.key) || !validApplicationCors(value.cors)
22
+ || Object.keys(value).some(key => !['kind', 'key', 'name', 'description', 'cors', 'invocationPolicy', 'anonymousAccess'].includes(key)))
23
+ return false;
24
+ if (value.invocationPolicy != null && !validPortableApplicationInvocationPolicy(value.invocationPolicy) || value.anonymousAccess != null && !validApplicationAnonymousAccess(value.anonymousAccess))
25
+ return false;
26
+ if (value.key === '@default')
27
+ return value.name === undefined && value.description === undefined
28
+ && validateRequestContract('UpdateEndpointServiceDto', { version: 0, cors: value.cors }).length === 0;
29
+ const { kind: _kind, invocationPolicy: _policy, anonymousAccess: _anonymous, ...payload } = value;
30
+ return typeof value.name === 'string' && value.name === value.name.trim()
31
+ && validateRequestContract('CreateEndpointServiceDto', payload).length === 0;
32
+ }
33
+ export function applicationItemAction(item) {
34
+ if (item.status === 'create')
35
+ return 'create';
36
+ if (item.status === 'orphan' || item.status === 'skipped')
37
+ return 'excluded';
38
+ if (item.status === 'clean')
39
+ return 'noop';
40
+ if (!item.desiredHash)
41
+ return 'blocked';
42
+ return item.desiredHash === item.currentHash ? 'adopt' : 'update';
43
+ }
44
+ export async function applicationManifestFromRecord(record, client, stableKeyName = 'stableKey') {
45
+ if (record.system !== (record.key === '@default') || typeof record.serviceId !== 'string' || !record.serviceId
46
+ || record.system !== (record.serviceId === DEFAULT_ENDPOINT_APPLICATION_ID)
47
+ || !Number.isInteger(record.version) || record.version < 0)
48
+ throw new Error('Incomplete or ambiguous Application identity.');
49
+ const manifest = { kind: 'application', key: record.key,
50
+ ...(record.system ? {} : { name: record.name, description: record.description ?? null }), cors: record.cors };
51
+ if (record.invocationPolicy !== undefined) {
52
+ if (record.invocationPolicy === null)
53
+ manifest.invocationPolicy = null;
54
+ else {
55
+ if (!client && (record.invocationPolicy.users.length || record.invocationPolicy.serviceAccounts.length))
56
+ throw new Error('Application principal projection requires the selected target client.');
57
+ manifest.invocationPolicy = await portableApplicationInvocationPolicy(client, record.invocationPolicy, stableKeyName);
58
+ }
59
+ }
60
+ if (record.anonymousAccess !== undefined)
61
+ manifest.anonymousAccess = record.anonymousAccess;
62
+ if (!validateApplicationManifest(manifest))
63
+ throw new Error(`Invalid Application definition for key "${record.key}".`);
64
+ return manifest;
65
+ }
66
+ export function hashPortableApplication(manifest) {
67
+ const canonical = structuredClone(manifest);
68
+ if (canonical.invocationPolicy?.groups?.length === 0)
69
+ delete canonical.invocationPolicy.groups;
70
+ return hashSyncDefinition('application', { ...canonical, ...(manifest.key === '@default' ? {} : { description: manifest.description ?? null }) });
71
+ }
72
+ export function applicationRevisionHash(record) {
73
+ return hashStable({ serviceId: record.serviceId, key: record.key, system: record.system, version: record.version,
74
+ name: record.name, description: record.description ?? null, cors: record.cors, invocationPolicy: record.invocationPolicy, anonymousAccess: record.anonymousAccess });
75
+ }
76
+ export async function loadRemoteApplications(client) {
77
+ const { applications } = await client.listAllApplications();
78
+ const keys = new Set(), ids = new Set();
79
+ for (const record of applications) {
80
+ await applicationManifestFromRecord({ ...record, invocationPolicy: undefined, anonymousAccess: undefined });
81
+ if (record.invocationPolicy != null && !validApplicationInvocationPolicy(record.invocationPolicy) || record.anonymousAccess != null && !validApplicationAnonymousAccess(record.anonymousAccess))
82
+ throw new Error('Invalid remote Application invocation or anonymous policy.');
83
+ if (keys.has(record.key) || ids.has(record.serviceId))
84
+ throw new Error(`Duplicate Application key or target identity "${record.key}".`);
85
+ keys.add(record.key);
86
+ ids.add(record.serviceId);
87
+ }
88
+ if (!keys.has('@default'))
89
+ throw new Error('Incomplete Applications catalog: the permanent system Default Application is missing.');
90
+ return applications;
91
+ }
92
+ export function readWorkspaceApplications(cwd) {
93
+ const { workspaceRoot } = requireProjectLayout(cwd, 'Application');
94
+ return findManifestFiles(path.join(workspaceRoot, 'Applications'), 'application.json').map(manifestPath => {
95
+ const value = readJsonFile(manifestPath);
96
+ if (!validateApplicationManifest(value))
97
+ throw new Error(`Invalid Application manifest "${localTargetPath(cwd, manifestPath)}". Applications use immutable key identity; Default permits only CORS and invocation/anonymous policies.`);
98
+ return { manifest: value, manifestPath };
99
+ });
100
+ }
101
+ function localByKey(cwd) {
102
+ const result = new Map();
103
+ for (const entry of readWorkspaceApplications(cwd)) {
104
+ if (result.has(entry.manifest.key))
105
+ throw new Error(`Duplicate local Application key "${entry.manifest.key}".`);
106
+ result.set(entry.manifest.key, entry);
107
+ }
108
+ return result;
109
+ }
110
+ function applicationBaseline(lock, key) {
111
+ return Object.hasOwn(lock.applications, key) ? lock.applications[key] : undefined;
112
+ }
113
+ function saveBaseline(input, manifest, manifestPath, remoteHash) {
114
+ const { projectRoot } = requireProjectLayout(input.cwd, 'Application');
115
+ const lock = readComponentLock(projectRoot);
116
+ const previous = applicationBaseline(lock, manifest.key);
117
+ lock.applications[manifest.key] = { stableKey: manifest.key, path: toPortableRelativePath(projectRoot, manifestPath),
118
+ sourceHash: withoutSyncOmit(() => hashPortableApplication(manifest)), environments: { ...(previous?.environments || {}),
119
+ [input.envName]: previous?.environments[input.envName]?.remoteHash === remoteHash ? previous.environments[input.envName]
120
+ : { remoteHash, syncedAt: new Date().toISOString() } } };
121
+ writeComponentLock(projectRoot, lock);
122
+ }
123
+ export async function pullApplicationsToWorkspace(input) {
124
+ const existing = localByKey(input.cwd);
125
+ let records;
126
+ try {
127
+ records = await loadRemoteApplications(input.client);
128
+ }
129
+ catch (error) {
130
+ if (applicationApiUnavailable(error) && input.allowUnsupported && existing.size === 0)
131
+ return { pulled: [], pruned: [], skipped: [{ targetPath: 'Applications', reason: 'Applications require Platform 1.9.2; legacy Default endpoints remain supported.' }] };
132
+ if (applicationApiUnavailable(error))
133
+ throw new Error('Applications require Platform 1.9.2; the selected API has no Applications catalog.', { cause: error });
134
+ throw error;
135
+ }
136
+ const { projectRoot, workspaceRoot } = requireProjectLayout(input.cwd, 'Application');
137
+ const lock = readComponentLock(projectRoot);
138
+ const incoming = await Promise.all(records.map(record => applicationManifestFromRecord(record, input.client, input.stableKeyName)));
139
+ const writes = incoming.map(value => {
140
+ const prior = existing.get(value.key);
141
+ const hash = hashPortableApplication(value);
142
+ const manifest = prior ? preserveOmittedProperties('application', value, prior.manifest) : value;
143
+ if (prior && !input.force && hashPortableApplication(prior.manifest) !== hash
144
+ && hashPortableApplication(prior.manifest) !== syncSourceBaselineHash('application', applicationBaseline(lock, value.key))) {
145
+ throw new Error(`Cannot pull Application "${value.key}": local definition changed since its baseline. Review or use --force.`);
146
+ }
147
+ return { manifest, hash, manifestPath: path.join(workspaceRoot, 'Applications', value.key === '@default' ? 'default' : value.key, 'application.json'), prior };
148
+ });
149
+ const removed = input.pruneOrphans ? [...existing.values()].filter(entry => !incoming.some(manifest => manifest.key === entry.manifest.key)) : [];
150
+ for (const write of writes) {
151
+ writePulledManifest({ filePath: write.manifestPath, manifest: write.manifest, previousPath: write.prior?.manifestPath, root: path.join(workspaceRoot, 'Applications'), force: input.force });
152
+ saveBaseline(input, write.manifest, write.manifestPath, write.hash);
153
+ }
154
+ if (removed.length) {
155
+ const current = readComponentLock(projectRoot);
156
+ for (const entry of removed) {
157
+ removeRelocatedManifest(entry.manifestPath, path.join(workspaceRoot, 'Applications'));
158
+ delete current.applications[entry.manifest.key];
159
+ }
160
+ writeComponentLock(projectRoot, current);
161
+ }
162
+ return { pulled: writes.map(write => ({ manifest: write.manifest, targetPath: localTargetPath(input.cwd, write.manifestPath) })),
163
+ pruned: removed.map(entry => ({ stableKey: entry.manifest.key, targetPath: localTargetPath(input.cwd, entry.manifestPath) })), skipped: [] };
164
+ }
165
+ async function effectiveApplication(input, source, target) {
166
+ const effective = structuredClone(target ? preserveOmittedProperties('application', source, target) : source);
167
+ for (const field of ['invocationPolicy', 'anonymousAccess'])
168
+ if (source[field] === undefined && target?.[field] !== undefined)
169
+ Object.assign(effective, { [field]: target[field] });
170
+ if (effective.invocationPolicy && source.invocationPolicy?.groups === undefined && target?.invocationPolicy?.groups !== undefined)
171
+ effective.invocationPolicy.groups = structuredClone(target.invocationPolicy.groups);
172
+ if (effective.invocationPolicy != null) {
173
+ effective.invocationPolicy = await canonicalApplicationInvocationPolicy(input, effective.invocationPolicy);
174
+ }
175
+ return effective;
176
+ }
177
+ export async function buildApplicationsPlan(input) {
178
+ const plan = { resourceType: 'application', env: input.envName,
179
+ counts: Object.fromEntries(statuses.map(status => [status, 0])), items: [], blockers: [], warnings: [], exclusions: [] };
180
+ try {
181
+ const local = localByKey(input.cwd);
182
+ let records;
183
+ try {
184
+ records = await loadRemoteApplications(input.client);
185
+ }
186
+ catch (error) {
187
+ if (applicationApiUnavailable(error) && input.allowUnsupported && local.size === 0) {
188
+ plan.exclusions.push('Applications require Platform 1.9.2; legacy Default endpoints remain supported.');
189
+ return plan;
190
+ }
191
+ if (applicationApiUnavailable(error))
192
+ throw new Error('Applications require Platform 1.9.2; the selected API has no Applications catalog.', { cause: error });
193
+ throw error;
194
+ }
195
+ const lock = readComponentLock(requireProjectLayout(input.cwd, 'Application').projectRoot);
196
+ for (const [key, entry] of local) {
197
+ const target = records.find(record => record.key === key);
198
+ const desiredHash = hashPortableApplication(entry.manifest);
199
+ const current = target ? await applicationManifestFromRecord(target, input.client, input.stableKeyName) : undefined;
200
+ const effective = await effectiveApplication(input, entry.manifest, current);
201
+ if (!validateApplicationManifest(effective))
202
+ throw new Error('Invalid effective Application definition after preserving omitted fields.');
203
+ const desired = hashPortableApplication(effective);
204
+ const currentHash = current ? hashPortableApplication(current) : undefined;
205
+ const baselineHash = syncBaselineHash('application', applicationBaseline(lock, key)?.environments[input.envName]);
206
+ const status = !target ? key === '@default' ? 'conflict' : 'create'
207
+ : desired === currentHash ? 'clean' : !baselineHash ? 'missing-lock' : baselineHash === currentHash ? 'safe-update'
208
+ : desiredHash === syncSourceBaselineHash('application', applicationBaseline(lock, key)) ? 'remote-changed' : 'conflict';
209
+ const changedFields = current ? ['name', 'description', 'cors', 'invocationPolicy', 'anonymousAccess'].filter(field => hashStable(effective[field] ?? null) !== hashStable(current[field] ?? null)) : [];
210
+ plan.items.push({ stableKey: key, name: entry.manifest.name ?? 'Default', status, desiredHash: desired, currentHash, baselineHash,
211
+ groupFences: await applicationGroupFences(input, effective.invocationPolicy), humanFences: await applicationHumanFences(input.client, effective.invocationPolicy), principalFences: await applicationPrincipalFences(input, effective.invocationPolicy), mappingHash: hashStable(applicationUserMappings(input.cwd, input.envName)), ...(target ? { targetRevisionHash: applicationRevisionHash(target) } : {}), changedFields });
212
+ if (!target && key === '@default')
213
+ plan.blockers.push('The target system Default Application is missing; it cannot be created by CLI.');
214
+ }
215
+ for (const target of records.filter(record => !local.has(record.key) && !record.system)) {
216
+ plan.items.push({ stableKey: target.key, name: target.name, status: 'orphan', currentHash: hashPortableApplication(await applicationManifestFromRecord(target, input.client, input.stableKeyName)), targetRevisionHash: applicationRevisionHash(target) });
217
+ }
218
+ }
219
+ catch (error) {
220
+ plan.blockers.push(error instanceof Error ? error.message : String(error));
221
+ }
222
+ for (const item of plan.items)
223
+ plan.counts[item.status]++;
224
+ return plan;
225
+ }
226
+ export async function pushApplications(input) {
227
+ const plan = input.reviewedPlan ?? await buildApplicationsPlan(input);
228
+ if (plan.blockers.length)
229
+ throw new Error(`Application push blocked: ${plan.blockers.join(' ')}`);
230
+ if (!input.force && plan.items.some(item => ['missing-lock', 'remote-changed', 'conflict'].includes(item.status)))
231
+ throw new Error('Application push blocked by target drift; review the plan before using --force.');
232
+ const local = localByKey(input.cwd);
233
+ if (input.reviewedPlan && hashStable([...local.keys()].sort()) !== hashStable(plan.items.filter(item => item.desiredHash).map(item => item.stableKey).sort())) {
234
+ throw new Error('Application source identities changed after the reviewed plan.');
235
+ }
236
+ const results = [];
237
+ for (const item of plan.items) {
238
+ const entry = local.get(item.stableKey);
239
+ const targetPath = entry ? localTargetPath(input.cwd, entry.manifestPath) : item.stableKey;
240
+ if (!entry || item.status === 'orphan') {
241
+ results.push({ stableKey: item.stableKey, action: 'orphan', status: 'skipped', targetPath });
242
+ continue;
243
+ }
244
+ try {
245
+ if (item.mappingHash !== hashStable(applicationUserMappings(input.cwd, input.envName)))
246
+ throw new Error('Application user mappings changed after planning; prepare a new reviewed plan.');
247
+ const freshLocal = localByKey(input.cwd).get(item.stableKey);
248
+ if (!freshLocal || hashPortableApplication(freshLocal.manifest) !== hashPortableApplication(entry.manifest))
249
+ throw new Error('Application source changed after planning.');
250
+ const records = await loadRemoteApplications(input.client);
251
+ const target = records.find(record => record.key === item.stableKey);
252
+ if (item.targetRevisionHash !== (target ? applicationRevisionHash(target) : undefined))
253
+ throw new Error('Application target identity or revision changed after planning.');
254
+ const current = target ? await applicationManifestFromRecord(target, input.client, input.stableKeyName) : undefined;
255
+ const effective = await effectiveApplication(input, entry.manifest, current);
256
+ if (!validateApplicationManifest(effective))
257
+ throw new Error('Invalid effective Application definition after preserving omitted fields.');
258
+ if (hashPortableApplication(effective) !== item.desiredHash)
259
+ throw new Error('Application source or omitted target state changed after the reviewed plan.');
260
+ const action = item.status === 'create' ? 'create' : item.status === 'clean' ? 'noop' : 'update';
261
+ if (item.humanFences && hashStable(item.humanFences) !== hashStable(await applicationHumanFences(input.client, effective.invocationPolicy)))
262
+ throw new Error('Application human account identity or revision changed after planning.');
263
+ const freshFences = await applicationPrincipalFences(input, effective.invocationPolicy);
264
+ const freshGroupFences = await applicationGroupFences(input, effective.invocationPolicy);
265
+ for (const expected of item.groupFences ?? []) {
266
+ const receipts = input.verifiedGroups?.filter(receipt => receipt.stableKey === expected.reference.stableKey) ?? [];
267
+ if (receipts.length > 1)
268
+ throw new Error('Ambiguous verified Group dependency.');
269
+ const receipt = receipts[0];
270
+ if (receipt && expected.groupId && receipt.groupId !== expected.groupId)
271
+ throw new Error('Verified Group cannot replace the reviewed physical identity.');
272
+ const groupId = receipt?.groupId ?? expected.groupId, revisionHash = receipt?.revisionHash ?? expected.revisionHash;
273
+ if (!groupId || !freshGroupFences.some(actual => actual.reference.stableKey === expected.reference.stableKey && actual.groupId === groupId && actual.revisionHash === revisionHash))
274
+ throw new Error('Application Group identity or revision changed after planning or verified identity deployment.');
275
+ }
276
+ for (const expected of item.principalFences ?? []) {
277
+ const receipts = expected.principal.kind === 'service-account' ? input.verifiedServiceAccounts?.filter(receipt => receipt.stableKey === expected.principal.stableKey) ?? [] : [];
278
+ if (receipts.length > 1)
279
+ throw new Error('Ambiguous verified Service Account dependency.');
280
+ const receipt = receipts[0];
281
+ if (receipt && expected.userId && receipt.userId !== expected.userId)
282
+ throw new Error('Verified Service Account cannot replace an existing reviewed principal identity.');
283
+ const userId = receipt?.userId ?? expected.userId;
284
+ const revisionHash = receipt?.revisionHash ?? expected.revisionHash;
285
+ if (!userId || !freshFences.some(actual => hashStable(actual.principal) === hashStable(expected.principal) && actual.userId === userId && actual.revisionHash === revisionHash))
286
+ throw new Error('Application Service Account identity or revision changed after planning or verified identity deployment.');
287
+ }
288
+ const policies = { ...(effective.invocationPolicy === undefined || target && (entry.manifest.invocationPolicy === undefined || omitPaths('application').some(parts => parts[0] === 'invocationPolicy')) ? {} : { invocationPolicy: effective.invocationPolicy === null ? null : await resolveApplicationInvocationPolicy(input, effective.invocationPolicy) }), ...(effective.anonymousAccess === undefined || target && (entry.manifest.anonymousAccess === undefined || omitPaths('application').some(parts => parts[0] === 'anonymousAccess')) ? {} : { anonymousAccess: effective.anonymousAccess }) };
289
+ if (item.mappingHash !== hashStable(applicationUserMappings(input.cwd, input.envName)))
290
+ throw new Error('Application user mappings changed before writing.');
291
+ let written = target;
292
+ if (action === 'create') {
293
+ if (effective.key === '@default')
294
+ throw new Error('The system Default Application cannot be created.');
295
+ written = await input.client.createApplication({ key: effective.key, name: effective.name, description: effective.description ?? null, cors: effective.cors, ...policies });
296
+ }
297
+ else if (action === 'update') {
298
+ if (!target)
299
+ throw new Error('Application target disappeared.');
300
+ const payload = effective.key === '@default' ? { version: target.version, cors: effective.cors, ...policies }
301
+ : { version: target.version, name: effective.name, description: effective.description ?? null, cors: effective.cors, ...policies };
302
+ written = await input.client.updateApplication(target.serviceId, payload);
303
+ }
304
+ if (!written || written.key !== effective.key || target && written.serviceId !== target.serviceId
305
+ || !Number.isInteger(written.version) || written.version !== (target ? target.version + (action === 'update' ? 1 : 0) : 0))
306
+ throw new Error('Application write returned an unexpected target identity or revision.');
307
+ if (hashPortableApplication(await applicationManifestFromRecord(written, input.client, input.stableKeyName)) !== hashPortableApplication(effective))
308
+ throw new Error('Application write response does not match the desired definition.');
309
+ const verified = (await loadRemoteApplications(input.client)).find(record => record.serviceId === written.serviceId);
310
+ if (!verified || verified.key !== effective.key || verified.version !== written.version || hashPortableApplication(await applicationManifestFromRecord(verified, input.client, input.stableKeyName)) !== hashPortableApplication(effective))
311
+ throw new Error('Application readback does not match the written identity, revision or definition.');
312
+ if (hashStable(freshGroupFences) !== hashStable(await applicationGroupFences(input, effective.invocationPolicy))
313
+ || hashStable(freshFences) !== hashStable(await applicationPrincipalFences(input, effective.invocationPolicy))
314
+ || item.humanFences && hashStable(item.humanFences) !== hashStable(await applicationHumanFences(input.client, effective.invocationPolicy))
315
+ || item.mappingHash !== hashStable(applicationUserMappings(input.cwd, input.envName)))
316
+ throw new Error('Application principal dependencies changed during write/readback; baseline was not advanced.');
317
+ if (current)
318
+ assertOmittedPropertiesPreserved('application', current, await applicationManifestFromRecord(verified, input.client, input.stableKeyName));
319
+ saveBaseline(input, entry.manifest, entry.manifestPath, hashPortableApplication(effective));
320
+ results.push({ stableKey: item.stableKey, action, status: action === 'noop' ? 'skipped' : 'deployed', targetPath,
321
+ verifiedApplication: { key: verified.key, serviceId: verified.serviceId, version: verified.version, desiredHash: hashPortableApplication(await applicationManifestFromRecord(verified, input.client, input.stableKeyName)), revisionHash: applicationRevisionHash(verified) } });
322
+ }
323
+ catch (error) {
324
+ results.push({ stableKey: item.stableKey, action: item.status === 'create' ? 'create' : 'update', status: 'failed', targetPath, error: error instanceof Error ? error.message : String(error) });
325
+ }
326
+ }
327
+ return { plan, results };
328
+ }