@zitadel/cli 0.1.0-alpha.12 → 0.1.0-alpha.14

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 (43) hide show
  1. package/README.md +137 -57
  2. package/SKILLS.md +26 -13
  3. package/dist/commands/apply.mjs +6 -4
  4. package/dist/commands/apply.mjs.map +1 -1
  5. package/dist/commands/doctor.mjs +89 -12
  6. package/dist/commands/doctor.mjs.map +1 -1
  7. package/dist/commands/eject.mjs +4 -4
  8. package/dist/commands/logs.mjs +2 -2
  9. package/dist/commands/plan.mjs +6 -4
  10. package/dist/commands/plan.mjs.map +1 -1
  11. package/dist/commands/reset.mjs +2 -2
  12. package/dist/commands/schemas/list.mjs +134 -0
  13. package/dist/commands/schemas/list.mjs.map +1 -0
  14. package/dist/commands/setup.mjs +130 -15
  15. package/dist/commands/setup.mjs.map +1 -1
  16. package/dist/commands/start.mjs +4 -4
  17. package/dist/commands/status.mjs +3 -3
  18. package/dist/commands/stop.mjs +3 -3
  19. package/dist/{docker-Djz6BLp9.mjs → docker-D7BSD5C9.mjs} +3 -3
  20. package/dist/{docker-Djz6BLp9.mjs.map → docker-D7BSD5C9.mjs.map} +1 -1
  21. package/dist/{docker-guidance-D-33g1uV.mjs → docker-guidance-mcTT3_0E.mjs} +2 -2
  22. package/dist/{docker-guidance-D-33g1uV.mjs.map → docker-guidance-mcTT3_0E.mjs.map} +1 -1
  23. package/dist/environment-BQF7LeCz.mjs +17 -0
  24. package/dist/environment-BQF7LeCz.mjs.map +1 -0
  25. package/dist/{oclif-BoUVygsZ.mjs → oclif-Bm-FkF6z.mjs} +66 -13
  26. package/dist/oclif-Bm-FkF6z.mjs.map +1 -0
  27. package/dist/{orca-DU8myWGm.mjs → orca-CpXj_XsA.mjs} +46 -94
  28. package/dist/orca-CpXj_XsA.mjs.map +1 -0
  29. package/dist/{ports-B09RjuHx.mjs → ports-CxBKS1ga.mjs} +1 -1
  30. package/dist/{ports-B09RjuHx.mjs.map → ports-CxBKS1ga.mjs.map} +1 -1
  31. package/dist/{processes-Cw8TO1SY.mjs → processes-BVqYsxT8.mjs} +1 -1
  32. package/dist/{processes-Cw8TO1SY.mjs.map → processes-BVqYsxT8.mjs.map} +1 -1
  33. package/dist/{project-B1qVQMKS.mjs → project-Dk7V0xka.mjs} +3 -3
  34. package/dist/{project-B1qVQMKS.mjs.map → project-Dk7V0xka.mjs.map} +1 -1
  35. package/dist/{sync-CzruNz8K.mjs → sync-nSLnVhKK.mjs} +128 -107
  36. package/dist/sync-nSLnVhKK.mjs.map +1 -0
  37. package/dist/user-schema-DDz5-lX5.mjs +13 -0
  38. package/dist/user-schema-DDz5-lX5.mjs.map +1 -0
  39. package/oclif.manifest.json +106 -1
  40. package/package.json +5 -4
  41. package/dist/oclif-BoUVygsZ.mjs.map +0 -1
  42. package/dist/orca-DU8myWGm.mjs.map +0 -1
  43. package/dist/sync-CzruNz8K.mjs.map +0 -1
@@ -1,6 +1,6 @@
1
- import { C as isObject, E as ZitadelError, w as parseJsonObject } from "./oclif-BoUVygsZ.mjs";
2
- import { join } from "node:path";
1
+ import { C as isObject, E as ZitadelError, w as parseJsonObject } from "./oclif-Bm-FkF6z.mjs";
3
2
  import { readFile, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
4
  //#region src/lib/project.ts
5
5
  /**
6
6
  * Reports whether `cwd` has already been initialized, i.e. a committed
@@ -84,4 +84,4 @@ function isNotFound(error) {
84
84
  //#endregion
85
85
  export { readZitadelConfig as a, readRendererId as i, hasZitadelSecret as n, readZitadelSecret as o, readDevelopmentIssuer as r, hasZitadelConfig as t };
86
86
 
87
- //# sourceMappingURL=project-B1qVQMKS.mjs.map
87
+ //# sourceMappingURL=project-Dk7V0xka.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"project-B1qVQMKS.mjs","names":[],"sources":["../src/lib/project.ts"],"sourcesContent":["import { readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ZitadelError } from \"./errors\";\nimport { isObject, parseJsonObject } from \"./json\";\n\n/**\n * Reports whether `cwd` has already been initialized, i.e. a committed\n * `zitadel.json` exists. Used to decide whether setup should run or skip.\n */\nexport async function hasZitadelConfig(cwd: string): Promise<boolean> {\n return exists(join(cwd, \"zitadel.json\"));\n}\n\n/**\n * Reports whether local secret material (`.zitadel/secret`) is present. Gates\n * commands that need credentials, and signals that secrets were already pulled.\n */\nexport async function hasZitadelSecret(cwd: string): Promise<boolean> {\n return exists(join(cwd, \".zitadel/secret\"));\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isNotFound(error)) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Shape of the project secret persisted at `.zitadel/secret`. Holds the\n * project identity plus the credentials used to talk to the platform in\n * preview and production. Validated structurally by {@link readZitadelSecret}.\n */\nexport type ZitadelSecret = {\n project_id: string;\n project_secret: string;\n preview_secret: string;\n preview_origins: string[];\n created_at: string;\n};\n\n/**\n * Reads and parses `zitadel.json` into a plain object. Translates a missing\n * file into an actionable `E_VALIDATION` error pointing at `zitadel setup`;\n * other errors (e.g. malformed JSON) propagate unchanged.\n */\nexport async function readZitadelConfig(cwd: string): Promise<Record<string, unknown>> {\n try {\n return parseJsonObject(await readFile(join(cwd, \"zitadel.json\"), \"utf8\"), \"zitadel.json\");\n } catch (error) {\n if (isNotFound(error)) {\n throw new ZitadelError(\"E_VALIDATION\", \"zitadel.json was not found\", {\n hint: \"Run `zitadel setup` first.\",\n nextCommands: [\"zitadel setup\"],\n });\n }\n throw error;\n }\n}\n\n/**\n * Reads, parses, and structurally validates `.zitadel/secret`, returning it\n * as a {@link ZitadelSecret}. A missing file becomes an actionable\n * `E_VALIDATION` error pointing at `zitadel setup` / `zitadel doctor --fix`;\n * a present-but-incomplete file throws so callers never proceed with partial\n * credentials.\n */\nexport async function readZitadelSecret(cwd: string): Promise<ZitadelSecret> {\n try {\n const secret = parseJsonObject(\n await readFile(join(cwd, \".zitadel/secret\"), \"utf8\"),\n \".zitadel/secret\",\n );\n if (\n typeof secret.project_id !== \"string\" ||\n typeof secret.project_secret !== \"string\" ||\n typeof secret.preview_secret !== \"string\" ||\n !Array.isArray(secret.preview_origins)\n ) {\n throw new Error(\".zitadel/secret is missing required fields\");\n }\n return secret as ZitadelSecret;\n } catch (error) {\n if (isNotFound(error)) {\n throw new ZitadelError(\"E_VALIDATION\", \".zitadel/secret was not found\", {\n hint: \"Run `zitadel setup` first, or restore the project secret with `zitadel doctor --fix`.\",\n nextCommands: [\"zitadel setup\", \"zitadel doctor --fix\"],\n });\n }\n throw error;\n }\n}\n\n/**\n * Reads the configured renderer id from a parsed `zitadel.json`, normalising the\n * legacy `default` alias to `react` and falling back to `react` when unset. The\n * value is validated downstream by `getRenderer`, so callers need not re-check.\n */\nexport function readRendererId(config: Record<string, unknown>): string {\n const branding = isObject(config.branding) ? config.branding : undefined;\n const value = branding && typeof branding.renderer === \"string\" ? branding.renderer : \"react\";\n return value === \"default\" ? \"react\" : value;\n}\n\n/** Reads `environments.development.issuer` from a parsed `zitadel.json`, if present. */\nexport function readDevelopmentIssuer(config: Record<string, unknown>): string | undefined {\n if (isObject(config.environments) && isObject(config.environments.development)) {\n const issuer = config.environments.development.issuer;\n return typeof issuer === \"string\" ? issuer : undefined;\n }\n return undefined;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === \"ENOENT\"\n );\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,iBAAiB,KAA+B;AACpE,QAAO,OAAO,KAAK,KAAK,eAAe,CAAC;;;;;;AAO1C,eAAsB,iBAAiB,KAA+B;AACpE,QAAO,OAAO,KAAK,KAAK,kBAAkB,CAAC;;AAG7C,eAAe,OAAO,MAAgC;AACpD,KAAI;AACF,QAAM,KAAK,KAAK;AAChB,SAAO;UACA,OAAO;AACd,MAAI,WAAW,MAAM,CACnB,QAAO;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ib/project.ts"],"sourcesContent":["import { readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ZitadelError } from \"./errors\";\nimport { isObject, parseJsonObject } from \"./json\";\n\n/**\n * Reports whether `cwd` has already been initialized, i.e. a committed\n * `zitadel.json` exists. Used to decide whether setup should run or skip.\n */\nexport async function hasZitadelConfig(cwd: string): Promise<boolean> {\n return exists(join(cwd, \"zitadel.json\"));\n}\n\n/**\n * Reports whether local secret material (`.zitadel/secret`) is present. Gates\n * commands that need credentials, and signals that secrets were already pulled.\n */\nexport async function hasZitadelSecret(cwd: string): Promise<boolean> {\n return exists(join(cwd, \".zitadel/secret\"));\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isNotFound(error)) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Shape of the project secret persisted at `.zitadel/secret`. Holds the\n * project identity plus the credentials used to talk to the platform in\n * preview and production. Validated structurally by {@link readZitadelSecret}.\n */\nexport type ZitadelSecret = {\n project_id: string;\n project_secret: string;\n preview_secret: string;\n preview_origins: string[];\n created_at: string;\n};\n\n/**\n * Reads and parses `zitadel.json` into a plain object. Translates a missing\n * file into an actionable `E_VALIDATION` error pointing at `zitadel setup`;\n * other errors (e.g. malformed JSON) propagate unchanged.\n */\nexport async function readZitadelConfig(cwd: string): Promise<Record<string, unknown>> {\n try {\n return parseJsonObject(await readFile(join(cwd, \"zitadel.json\"), \"utf8\"), \"zitadel.json\");\n } catch (error) {\n if (isNotFound(error)) {\n throw new ZitadelError(\"E_VALIDATION\", \"zitadel.json was not found\", {\n hint: \"Run `zitadel setup` first.\",\n nextCommands: [\"zitadel setup\"],\n });\n }\n throw error;\n }\n}\n\n/**\n * Reads, parses, and structurally validates `.zitadel/secret`, returning it\n * as a {@link ZitadelSecret}. A missing file becomes an actionable\n * `E_VALIDATION` error pointing at `zitadel setup` / `zitadel doctor --fix`;\n * a present-but-incomplete file throws so callers never proceed with partial\n * credentials.\n */\nexport async function readZitadelSecret(cwd: string): Promise<ZitadelSecret> {\n try {\n const secret = parseJsonObject(\n await readFile(join(cwd, \".zitadel/secret\"), \"utf8\"),\n \".zitadel/secret\",\n );\n if (\n typeof secret.project_id !== \"string\" ||\n typeof secret.project_secret !== \"string\" ||\n typeof secret.preview_secret !== \"string\" ||\n !Array.isArray(secret.preview_origins)\n ) {\n throw new Error(\".zitadel/secret is missing required fields\");\n }\n return secret as ZitadelSecret;\n } catch (error) {\n if (isNotFound(error)) {\n throw new ZitadelError(\"E_VALIDATION\", \".zitadel/secret was not found\", {\n hint: \"Run `zitadel setup` first, or restore the project secret with `zitadel doctor --fix`.\",\n nextCommands: [\"zitadel setup\", \"zitadel doctor --fix\"],\n });\n }\n throw error;\n }\n}\n\n/**\n * Reads the configured renderer id from a parsed `zitadel.json`, normalising the\n * legacy `default` alias to `react` and falling back to `react` when unset. The\n * value is validated downstream by `getRenderer`, so callers need not re-check.\n */\nexport function readRendererId(config: Record<string, unknown>): string {\n const branding = isObject(config.branding) ? config.branding : undefined;\n const value = branding && typeof branding.renderer === \"string\" ? branding.renderer : \"react\";\n return value === \"default\" ? \"react\" : value;\n}\n\n/** Reads `environments.development.issuer` from a parsed `zitadel.json`, if present. */\nexport function readDevelopmentIssuer(config: Record<string, unknown>): string | undefined {\n if (isObject(config.environments) && isObject(config.environments.development)) {\n const issuer = config.environments.development.issuer;\n return typeof issuer === \"string\" ? issuer : undefined;\n }\n return undefined;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === \"ENOENT\"\n );\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,iBAAiB,KAA+B;AACpE,QAAO,OAAO,KAAK,KAAK,eAAe,CAAC;;;;;;AAO1C,eAAsB,iBAAiB,KAA+B;AACpE,QAAO,OAAO,KAAK,KAAK,kBAAkB,CAAC;;AAG7C,eAAe,OAAO,MAAgC;AACpD,KAAI;AACF,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AAU,SACT,MAA4B,SAAS"}
@@ -1,64 +1,11 @@
1
- import { C as isObject, E as ZitadelError } from "./oclif-BoUVygsZ.mjs";
1
+ import { C as isObject, E as ZitadelError } from "./oclif-Bm-FkF6z.mjs";
2
+ import { t as SCHEMAS_DIR } from "./user-schema-DDz5-lX5.mjs";
3
+ import { readFile, readdir, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
2
5
  import { consola as consola$1 } from "consola";
3
6
  import { createHash } from "node:crypto";
4
- import { join } from "node:path";
5
- import { readFile, readdir, writeFile } from "node:fs/promises";
6
- import { z } from "zod";
7
- import { CreateFlowDefinitionBody, CreateSchemaBody } from "@zitadel/api/generated/endpoints/zitadelNextGen.zod";
8
- //#region src/lib/environment.ts
9
- /**
10
- * CLI-side deployment environment. Not an API model — it gates which
11
- * `zitadel.json` environment block and server the commands target.
12
- * Project request/response shapes live in `@zitadel/api`
13
- * (generated from the OpenAPI spec).
14
- */
15
- const environmentSchema = z.enum([
16
- "development",
17
- "preview",
18
- "production"
19
- ]);
20
- //#endregion
21
- //#region src/lib/flows/validate.ts
22
- /**
23
- * The generated `CreateFlowDefinitionBody` Zod schema describes the
24
- * full envelope (`{project_id, flow_definition, schema_uri?}`); the
25
- * on-disk flow body is just the inner `flow_definition` shape. Pull
26
- * that out via `.shape` so on-disk validation runs against exactly the
27
- * same schema the wire request validates against.
28
- */
29
- const flowDefinitionBodySchema = CreateFlowDefinitionBody.shape.flow_definition;
30
- /**
31
- * Validate raw JSON bodies against the generated flow-definition Zod
32
- * schema (the orval-emitted equivalent of
33
- * `api/openapi/components/flows/flow-definition.yaml`). Errors from
34
- * every input are collected and rethrown as a single `E_VALIDATION`
35
- * `ZitadelError` so callers see the full picture at once rather than
36
- * failing on the first malformed entry.
37
- *
38
- * Pure: does not touch the filesystem or network. The input array
39
- * is read-only; the returned array is freshly allocated.
40
- *
41
- * @param flows - Raw values to validate. Unknown-typed so callers
42
- * can pass freshly-parsed JSON without first asserting a shape.
43
- */
44
- function validateFlows(flows) {
45
- const issues = [];
46
- const parsed = [];
47
- for (let i = 0; i < flows.length; i += 1) {
48
- const result = flowDefinitionBodySchema.safeParse(flows[i]);
49
- if (!result.success) {
50
- issues.push({
51
- index: i,
52
- issues: result.error.issues
53
- });
54
- continue;
55
- }
56
- parsed.push(result.data);
57
- }
58
- if (issues.length > 0) throw new ZitadelError("E_VALIDATION", "One or more flow definitions are invalid", { details: { issues } });
59
- return parsed;
60
- }
61
- //#endregion
7
+ import { DEFAULT_FLOW_SCHEMA_URI } from "@zitadel/config/defaults";
8
+ import { flowConfigSchema, schemaConfigSchema } from "@zitadel/config/schemas";
62
9
  //#region src/lib/flows/env-refs.ts
63
10
  /**
64
11
  * Collects the environment variables a flows document depends on, sorted and
@@ -92,24 +39,14 @@ function flowEnvRefs(value) {
92
39
  */
93
40
  const FLOWS_DIR = ".zitadel/flows";
94
41
  //#endregion
95
- //#region src/lib/user-schema/index.ts
96
- /**
97
- * Relative directory (from the project root) where local user-schema
98
- * files live. Owned here so callers (`commands/*`, `sync/syncers.ts`)
99
- * and tests share a single source of truth for the path; the runtime
100
- * never depends on it directly because `lib/user-schema` does not touch
101
- * the filesystem. The counterpart of `lib/flows`' `FLOWS_DIR`.
102
- */
103
- const SCHEMAS_DIR = ".zitadel/schemas";
104
- //#endregion
105
42
  //#region src/lib/sync/syncers.ts
106
43
  /**
107
44
  * Build the syncer list with the context every syncer needs: the
108
45
  * `project_id` flow creates carry, and the runtime `env` against which
109
- * each file's `${VAR}` / `*_env` references are checked. Callers
110
- * (apply / plan / setup) read `project_id` from `.zitadel/secret` and
111
- * pass the process environment. The returned array is treated as
112
- * read-only by the sync loop.
46
+ * each file's `${VAR}` / `*_env` references are checked. Callers (apply /
47
+ * plan / setup) read `project_id` from `.zitadel/secret` and pass the
48
+ * process environment. The returned array is treated as read-only by the
49
+ * sync loop.
113
50
  */
114
51
  function makeSyncers(opts) {
115
52
  return [new SchemaSyncer(opts.client, opts.projectId, opts.env), new FlowDefinitionSyncer(opts.client, opts.projectId, opts.env)];
@@ -128,6 +65,7 @@ var SchemaSyncer = class {
128
65
  kind = "schema";
129
66
  directory = SCHEMAS_DIR;
130
67
  mutable = false;
68
+ revisioned = true;
131
69
  constructor(client, projectId, env) {
132
70
  this.client = client;
133
71
  this.projectId = projectId;
@@ -140,38 +78,50 @@ var SchemaSyncer = class {
140
78
  * discriminated on `kind`; both are valid on-disk bodies.
141
79
  */
142
80
  validate(data) {
143
- const result = CreateSchemaBody.safeParse(data);
81
+ const result = schemaConfigSchema.safeParse(data);
144
82
  if (!result.success) throw new ZitadelError("E_VALIDATION", "Schema file is not a valid Zitadel schema body", { details: { issues: result.error.issues } });
145
83
  assertEnvRefs(data, this.env);
146
84
  }
85
+ /**
86
+ * `POST /schemas` mints a new immutable row. The server allocates the
87
+ * opaque id; the CLI records it in state and re-pins flows against it.
88
+ */
147
89
  async create(data) {
148
90
  return (await this.client.createSchema(data, { project_id: this.projectId })).id;
149
91
  }
150
- /** Never called — schemas are immutable on the platform, so `mutable = false`. */
151
- async update(_id, _data) {}
92
+ /**
93
+ * Not called by the sync loop: schemas are `revisioned`, so a hash change
94
+ * publishes a new immutable revision through {@link create} rather than
95
+ * mutating an existing row. Kept as a required interface member; throws
96
+ * loudly if a caller reaches it.
97
+ */
98
+ async update(_id, _data) {
99
+ throw new ZitadelError("E_NOT_IMPLEMENTED", "schemas are revisioned — edit publishes a new revision, not an update");
100
+ }
152
101
  async delete(id) {
153
102
  throw new ZitadelError("E_NOT_IMPLEMENTED", `schema delete is not supported (${id})`);
154
103
  }
155
104
  async fetch(id) {
156
- return await this.client.getSchemaById(id, { project_id: this.projectId });
105
+ return await this.client.getSchemaById(encodeURIComponent(id), { project_id: this.projectId });
157
106
  }
158
107
  };
159
108
  var FlowDefinitionSyncer = class {
160
109
  kind = "flow";
161
110
  directory = FLOWS_DIR;
162
111
  mutable = true;
112
+ revisioned = false;
163
113
  constructor(client, projectId, env) {
164
114
  this.client = client;
165
115
  this.projectId = projectId;
166
116
  this.env = env;
167
117
  }
168
118
  /**
169
- * Validates one flow file. `validateFlows` takes a batch and throws
170
- * `E_VALIDATION` on the first invalid entry; passing a single-element array
171
- * lets us reuse the batch validator for one file.
119
+ * Validates one flow file against the canonical `flowConfigSchema` (the
120
+ * same Zod `validateFlows` and doctor use), then checks env references.
172
121
  */
173
122
  validate(data) {
174
- validateFlows([data]);
123
+ const result = flowConfigSchema.safeParse(data);
124
+ if (!result.success) throw new ZitadelError("E_VALIDATION", "Flow file is not a valid Zitadel flow body", { details: { issues: result.error.issues } });
175
125
  assertEnvRefs(data, this.env);
176
126
  }
177
127
  /**
@@ -184,6 +134,7 @@ var FlowDefinitionSyncer = class {
184
134
  async create(data) {
185
135
  return (await this.client.createFlowDefinition({
186
136
  project_id: this.projectId,
137
+ schema_uri: DEFAULT_FLOW_SCHEMA_URI,
187
138
  flow_definition: data
188
139
  })).id;
189
140
  }
@@ -198,18 +149,15 @@ var FlowDefinitionSyncer = class {
198
149
  await this.client.updateFlowDefinition(id, { flow_definition: data }, { project_id: this.projectId });
199
150
  }
200
151
  async delete(id) {
201
- await this.client.deleteFlowDefinition(id);
152
+ await this.client.deleteFlowDefinition(id, { project_id: this.projectId });
202
153
  }
203
154
  /**
204
- * `GET /flow_definitions/:id` wraps the bare flow body in a detail envelope
205
- * (`id`, `project_id`, `schema_uri`, `status`, `created_at`, `updated_at`).
206
- * Strip those envelope fields here so the diff renderer compares
207
- * apples-to-apples against the on-disk file, which stores only the bare
208
- * body.
155
+ * `GET /flow_definitions/:id` returns a detail envelope with metadata
156
+ * (`id`, `project_id`, `created_at`, `updated_at`) plus `flow_definition`.
157
+ * Return only `flow_definition` so diffs compare with the on-disk bare body.
209
158
  */
210
159
  async fetch(id) {
211
- const { id: _id, project_id: _projectId, schema_uri: _schemaUri, status: _status, created_at: _createdAt, updated_at: _updatedAt, ...body } = await this.client.getFlowDefinition(id);
212
- return body;
160
+ return (await this.client.getFlowDefinition(id, { project_id: this.projectId })).flow_definition;
213
161
  }
214
162
  };
215
163
  //#endregion
@@ -260,7 +208,7 @@ async function removeFromState(cwd, key) {
260
208
  /**
261
209
  * Compute the sync plan for `cwd` against the state file and (when
262
210
  * `fetchOld` is true) the platform API. The plan is read-only: it
263
- * decides what create/update/delete operations need to happen but
211
+ * decides what create/update/revise/delete operations need to happen but
264
212
  * performs none of them. Pass it to {@link runSyncLoop} to execute.
265
213
  *
266
214
  * Validates every on-disk file (via `syncer.validate`) before planning any
@@ -280,6 +228,7 @@ async function removeFromState(cwd, key) {
280
228
  async function buildSyncPlan(cwd, syncers, fetchOld = false) {
281
229
  const state = await readState(cwd);
282
230
  const actions = [];
231
+ const localFlows = await readLocalFlowUserSchemas(cwd);
283
232
  for (const syncer of syncers) {
284
233
  const dirPath = join(cwd, syncer.directory);
285
234
  consola$1.debug(`scanning ${syncer.directory}`);
@@ -305,7 +254,7 @@ async function buildSyncPlan(cwd, syncers, fetchOld = false) {
305
254
  for (const [absPath, content] of onDisk.entries()) {
306
255
  const relPath = absPath.slice(cwd.length + 1);
307
256
  const entry = state.resources[relPath];
308
- const hash = sha256(content);
257
+ const hash = hashResourceContent(content);
309
258
  if (!entry?.id) {
310
259
  actions.push({
311
260
  kind: "create",
@@ -316,28 +265,37 @@ async function buildSyncPlan(cwd, syncers, fetchOld = false) {
316
265
  });
317
266
  continue;
318
267
  }
319
- if (!syncer.mutable) {
268
+ if (entry.hash === hash) {
320
269
  actions.push({
321
270
  kind: "skip",
322
271
  path: relPath,
323
- reason: "immutable"
272
+ reason: "no-change"
324
273
  });
325
274
  continue;
326
275
  }
327
- if (entry.hash === hash) {
276
+ if (syncer.revisioned) {
277
+ const oldContent = await fetchOldIfAsked(syncer, entry.id, fetchOld);
328
278
  actions.push({
329
- kind: "skip",
279
+ kind: "revise",
330
280
  path: relPath,
331
- reason: "no-change"
281
+ syncer,
282
+ content,
283
+ hash,
284
+ previousId: entry.id,
285
+ oldContent,
286
+ affectedPaths: findFlowsPinnedTo(entry.id, localFlows)
332
287
  });
333
288
  continue;
334
289
  }
335
- let oldContent = null;
336
- if (fetchOld && syncer.fetch) try {
337
- oldContent = await syncer.fetch(entry.id);
338
- } catch (err) {
339
- consola$1.debug(`fetch ${syncer.kind} ${entry.id} failed:`, err);
290
+ if (!syncer.mutable) {
291
+ actions.push({
292
+ kind: "skip",
293
+ path: relPath,
294
+ reason: "immutable"
295
+ });
296
+ continue;
340
297
  }
298
+ const oldContent = await fetchOldIfAsked(syncer, entry.id, fetchOld);
341
299
  actions.push({
342
300
  kind: "update",
343
301
  path: relPath,
@@ -368,13 +326,25 @@ async function runSyncLoop(cwd, syncers) {
368
326
  for (const action of actions) switch (action.kind) {
369
327
  case "create": {
370
328
  const id = await action.syncer.create(action.content);
371
- await updateState(cwd, action.path, {
329
+ const entry = {
372
330
  id,
373
331
  hash: action.hash
374
- });
332
+ };
333
+ await updateState(cwd, action.path, entry);
375
334
  consola$1.info(`Created a new ${action.syncer.kind} on Zitadel from ${action.path} (id ${id})`);
376
335
  break;
377
336
  }
337
+ case "revise": {
338
+ const id = await action.syncer.create(action.content);
339
+ const entry = {
340
+ id,
341
+ hash: action.hash
342
+ };
343
+ await updateState(cwd, action.path, entry);
344
+ consola$1.info(`Published a new ${action.syncer.kind} revision on Zitadel from ${action.path} (id ${id})`);
345
+ if (action.affectedPaths.length > 0) consola$1.warn(`New ${action.syncer.kind} revision ${id}. Update user_schema in these flow definitions to adopt it:\n` + action.affectedPaths.map((path) => ` - ${path}`).join("\n"));
346
+ break;
347
+ }
378
348
  case "update":
379
349
  await action.syncer.update(action.id, action.content);
380
350
  await updateState(cwd, action.path, { hash: action.hash });
@@ -390,6 +360,15 @@ async function runSyncLoop(cwd, syncers) {
390
360
  break;
391
361
  }
392
362
  }
363
+ async function fetchOldIfAsked(syncer, id, fetchOld) {
364
+ if (!fetchOld || !syncer.fetch) return null;
365
+ try {
366
+ return await syncer.fetch(id);
367
+ } catch (err) {
368
+ consola$1.debug(`fetch ${syncer.kind} ${id} failed:`, err);
369
+ return null;
370
+ }
371
+ }
393
372
  async function readJsonDir(dirPath) {
394
373
  const result = /* @__PURE__ */ new Map();
395
374
  let entries;
@@ -406,7 +385,27 @@ async function readJsonDir(dirPath) {
406
385
  }
407
386
  return result;
408
387
  }
409
- function sha256(data) {
388
+ /**
389
+ * Walk `.zitadel/flows/*.json` once and return each flow's `user_schema` value
390
+ * keyed by project-root-relative path. A flow file without a `user_schema` (or
391
+ * with a non-string one) is skipped: it does not pin a schema revision, so it
392
+ * cannot be affected by one.
393
+ */
394
+ async function readLocalFlowUserSchemas(cwd) {
395
+ const result = /* @__PURE__ */ new Map();
396
+ const flows = await readJsonDir(join(cwd, FLOWS_DIR));
397
+ for (const [absPath, content] of flows.entries()) {
398
+ const relPath = absPath.slice(cwd.length + 1);
399
+ if (typeof content === "object" && content !== null && "user_schema" in content && typeof content.user_schema === "string") result.set(relPath, content.user_schema);
400
+ }
401
+ return result;
402
+ }
403
+ function findFlowsPinnedTo(previousId, localFlows) {
404
+ const affected = [];
405
+ for (const [relPath, ref] of localFlows.entries()) if (ref === previousId) affected.push(relPath);
406
+ return affected;
407
+ }
408
+ function hashResourceContent(data) {
410
409
  return createHash("sha256").update(JSON.stringify(data)).digest("hex");
411
410
  }
412
411
  //#endregion
@@ -421,6 +420,7 @@ function summarizePlan(actions) {
421
420
  return {
422
421
  creates: active.filter((a) => a.kind === "create").length,
423
422
  updates: active.filter((a) => a.kind === "update").length,
423
+ revisions: active.filter((a) => a.kind === "revise").length,
424
424
  deletes: active.filter((a) => a.kind === "delete").length,
425
425
  total: active.length
426
426
  };
@@ -444,10 +444,11 @@ function renderPlan(actions, tty) {
444
444
  out.push(...renderBlock(action, tty));
445
445
  }
446
446
  out.push("");
447
- const { creates, updates, deletes } = summarizePlan(actions);
447
+ const { creates, updates, revisions, deletes } = summarizePlan(actions);
448
448
  const parts = [];
449
449
  if (creates > 0) parts.push(`${creates} to add`);
450
450
  if (updates > 0) parts.push(`${updates} to change`);
451
+ if (revisions > 0) parts.push(`${revisions} new revision${revisions === 1 ? "" : "s"}`);
451
452
  if (deletes > 0) parts.push(`${deletes} to destroy`);
452
453
  out.push(paint(`Plan: ${parts.join(", ")}.`, A.bold, tty));
453
454
  return out.join("\n");
@@ -729,11 +730,31 @@ function renderBlock(action, tty) {
729
730
  lines.push(`${closePad}}`);
730
731
  break;
731
732
  }
733
+ case "revise": {
734
+ const header = `${blkPad}# ${action.path} will publish a new revision`;
735
+ const opening = `${blkPad}~ resource "${action.syncer.kind}" "${resourceName(action.path)}" {`;
736
+ lines.push(paint(header, A.bold, tty));
737
+ lines.push(paint(opening, A.yellow, tty));
738
+ if (action.oldContent) renderDiff({
739
+ id: action.previousId,
740
+ ...action.oldContent
741
+ }, {
742
+ id: KNOWN_AFTER_APPLY,
743
+ ...action.content
744
+ }, FIELD_COL, tty, lines);
745
+ else lines.push(`${" ".repeat(FIELD_COL)} # (field diff unavailable — no read endpoint for ${action.syncer.kind})`);
746
+ lines.push(`${closePad}}`);
747
+ if (action.affectedPaths.length > 0) {
748
+ lines.push(paint(`${blkPad}# after apply, update user_schema in these flow definitions:`, A.yellow, tty));
749
+ for (const path of action.affectedPaths) lines.push(paint(`${blkPad}# - ${path}`, A.yellow, tty));
750
+ }
751
+ break;
752
+ }
732
753
  case "skip": break;
733
754
  }
734
755
  return lines;
735
756
  }
736
757
  //#endregion
737
- export { makeSyncers as a, runSyncLoop as i, summarizePlan as n, environmentSchema as o, buildSyncPlan as r, renderPlan as t };
758
+ export { runSyncLoop as a, FLOWS_DIR as c, hashResourceContent as i, summarizePlan as n, updateState as o, buildSyncPlan as r, makeSyncers as s, renderPlan as t };
738
759
 
739
- //# sourceMappingURL=sync-CzruNz8K.mjs.map
760
+ //# sourceMappingURL=sync-nSLnVhKK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-nSLnVhKK.mjs","names":[],"sources":["../src/lib/flows/env-refs.ts","../src/lib/flows/index.ts","../src/lib/sync/syncers.ts","../src/lib/sync/state.ts","../src/lib/sync/loop.ts","../src/lib/sync/plan-renderer.ts"],"sourcesContent":["import { isObject } from \"../json\";\n\n/**\n * Collects the environment variables a flows document depends on, sorted and\n * de-duplicated. Recognises two reference styles: inline `${VAR}` interpolations\n * inside string values, and keys ending in `_env` whose value names a single\n * variable. `apply`/`plan` use this to fail before contacting the platform when\n * a required variable is absent.\n */\nexport function flowEnvRefs(value: unknown): string[] {\n const refs = new Set<string>();\n const visit = (node: unknown): void => {\n if (typeof node === \"string\") {\n for (const match of node.matchAll(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g)) {\n const ref = match[1];\n if (ref) {\n refs.add(ref);\n }\n }\n } else if (Array.isArray(node)) {\n node.forEach(visit);\n } else if (isObject(node)) {\n for (const [key, child] of Object.entries(node)) {\n if (key.endsWith(\"_env\") && typeof child === \"string\" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(child)) {\n refs.add(child);\n } else {\n visit(child);\n }\n }\n }\n };\n visit(value);\n return [...refs].sort();\n}\n","/**\n * Public surface for the flow domain. Every caller outside this module\n * imports from here (not from individual files) so the package\n * boundary stays observable.\n *\n * **Source of truth.** The wire shape lives in\n * `@zitadel/api/generated/model` (orval-generated from the\n * OpenAPI spec). Callers that need the type import\n * `CreateFlowDefinitionBodyFlowDefinition` from there directly;\n * callers that need the runtime validator import\n * `CreateFlowDefinitionBody` from\n * `@zitadel/api/generated/endpoints/zitadelNextGen.zod`. This\n * module owns only the CLI-specific concerns: the password-flow\n * builder, env-var reference scanning, and the file-level\n * `validateFlows` helper that surfaces `E_VALIDATION` errors against\n * the generated Zod.\n *\n * **Dependency rule.** No upward imports (`commands/`, `sync/`, etc.)\n * and no filesystem I/O. It depends sideways only on shared utilities\n * under `apps/cli/src/lib/` — today `lib/errors` (`ZitadelError`).\n */\nexport { buildFlow } from \"./build\";\nexport { validateFlows } from \"./validate\";\nexport { flowEnvRefs } from \"./env-refs\";\n\n/**\n * Relative directory (from the project root) where local flow files\n * live. Owned here so callers (`commands/*`, `sync/syncers.ts`) and\n * tests share a single source of truth for the path; the runtime\n * never depends on it directly because `lib/flows` does not touch\n * the filesystem.\n */\nexport const FLOWS_DIR = \".zitadel/flows\";\n","import type {\n CreateFlowDefinitionBodyFlowDefinition,\n UpdateFlowDefinitionBodyFlowDefinition,\n CreateSchemaBody,\n GetSchemaById200,\n GetFlowDefinition200,\n} from \"@zitadel/api/generated/model\";\nimport type { ZitadelClient } from \"@zitadel/api/client\";\nimport { DEFAULT_FLOW_SCHEMA_URI } from \"@zitadel/config/defaults\";\nimport { flowConfigSchema, schemaConfigSchema } from \"@zitadel/config/schemas\";\n\nimport { FLOWS_DIR, flowEnvRefs } from \"../flows\";\nimport { SCHEMAS_DIR } from \"../user-schema\";\nimport { ZitadelError } from \"../errors\";\nimport type { ResourceSyncer } from \"./types.js\";\n\n/** Runtime environment lookup used to resolve `${VAR}` / `*_env` references. */\ntype EnvLookup = Record<string, string | undefined>;\n\n/**\n * Build the syncer list with the context every syncer needs: the\n * `project_id` flow creates carry, and the runtime `env` against which\n * each file's `${VAR}` / `*_env` references are checked. Callers (apply /\n * plan / setup) read `project_id` from `.zitadel/secret` and pass the\n * process environment. The returned array is treated as read-only by the\n * sync loop.\n */\nexport function makeSyncers(opts: {\n client: ZitadelClient;\n projectId: string;\n env: EnvLookup;\n}): ReadonlyArray<ResourceSyncer> {\n return [\n new SchemaSyncer(opts.client, opts.projectId, opts.env),\n new FlowDefinitionSyncer(opts.client, opts.projectId, opts.env),\n ];\n}\n\n/**\n * Assert that every env var a resource references — `${VAR}` placeholders and\n * the `*_env` convention — is present in `env`, throwing `E_VALIDATION` listing\n * the missing names. Shared by every syncer so the check is identical for\n * schemas and flows, and runs in the sync engine before any platform call.\n */\nfunction assertEnvRefs(data: object, env: EnvLookup): void {\n const missing = flowEnvRefs(data).filter((name) => !env[name]);\n if (missing.length > 0) {\n throw new ZitadelError(\"E_VALIDATION\", `Missing environment variables: ${missing.join(\", \")}`);\n }\n}\n\nclass SchemaSyncer implements ResourceSyncer {\n readonly kind = \"schema\";\n readonly directory = SCHEMAS_DIR;\n readonly mutable = false;\n readonly revisioned = true;\n\n constructor(\n private readonly client: ZitadelClient,\n private readonly projectId: string,\n private readonly env: EnvLookup,\n ) {}\n\n /**\n * Parse against the generated `CreateSchemaBody` Zod (the orval-emitted\n * equivalent of `api/openapi/endpoints/schemas/user-schema.yaml`). The\n * generated schema is a union of `user-schema` and `schema-url`\n * discriminated on `kind`; both are valid on-disk bodies.\n */\n validate(data: object): void {\n const result = schemaConfigSchema.safeParse(data);\n if (!result.success) {\n throw new ZitadelError(\"E_VALIDATION\", \"Schema file is not a valid Zitadel schema body\", {\n details: { issues: result.error.issues },\n });\n }\n assertEnvRefs(data, this.env);\n }\n\n /**\n * `POST /schemas` mints a new immutable row. The server allocates the\n * opaque id; the CLI records it in state and re-pins flows against it.\n */\n async create(data: object): Promise<string> {\n const result = await this.client.createSchema(data as CreateSchemaBody, {\n project_id: this.projectId,\n });\n return result.id;\n }\n\n /**\n * Not called by the sync loop: schemas are `revisioned`, so a hash change\n * publishes a new immutable revision through {@link create} rather than\n * mutating an existing row. Kept as a required interface member; throws\n * loudly if a caller reaches it.\n */\n async update(_id: string, _data: object): Promise<void> {\n throw new ZitadelError(\"E_NOT_IMPLEMENTED\", \"schemas are revisioned — edit publishes a new revision, not an update\");\n }\n\n async delete(id: string): Promise<void> {\n // Schemas are immutable on the platform: no PATCH, no DELETE in the\n // generated client. The sync loop's delete branch (`loop.ts`) still\n // schedules a delete action when a state entry exists and the\n // on-disk file is gone — `mutable` only gates updates, not deletes.\n // We deliberately fail loud here so the user notices that removing\n // a schema file is not a supported way to retire it.\n throw new ZitadelError(\"E_NOT_IMPLEMENTED\", `schema delete is not supported (${id})`);\n }\n\n async fetch(id: string): Promise<object> {\n const body = await this.client.getSchemaById(encodeURIComponent(id), {\n project_id: this.projectId,\n });\n return body as unknown as GetSchemaById200;\n }\n}\n\nclass FlowDefinitionSyncer implements ResourceSyncer {\n readonly kind = \"flow\";\n readonly directory = FLOWS_DIR;\n readonly mutable = true;\n readonly revisioned = false;\n\n constructor(\n private readonly client: ZitadelClient,\n private readonly projectId: string,\n private readonly env: EnvLookup,\n ) {}\n\n /**\n * Validates one flow file against the canonical `flowConfigSchema` (the\n * same Zod `validateFlows` and doctor use), then checks env references.\n */\n validate(data: object): void {\n const result = flowConfigSchema.safeParse(data);\n if (!result.success) {\n throw new ZitadelError(\"E_VALIDATION\", \"Flow file is not a valid Zitadel flow body\", {\n details: { issues: result.error.issues },\n });\n }\n assertEnvRefs(data, this.env);\n }\n\n /**\n * Wraps the bare on-disk flow body in the spec's create-envelope\n * (`api/openapi/components/flows/flow-definition-create-request.yaml`)\n * before sending. The file on disk stays bare so it is human-editable;\n * only the wire request carries `project_id` and the surrounding\n * envelope.\n */\n async create(data: object): Promise<string> {\n const result = await this.client.createFlowDefinition({\n project_id: this.projectId,\n schema_uri: DEFAULT_FLOW_SCHEMA_URI,\n flow_definition: data as CreateFlowDefinitionBodyFlowDefinition,\n });\n return result.id;\n }\n\n /**\n * PUT completely replaces the flow definition. The wire request wraps the\n * bare on-disk flow in the `{ flow_definition }` update envelope\n * (`api/openapi/components/flows/flow-definition-update-request.yaml`) and\n * carries `project_id` as a query parameter; the file on disk stays bare so\n * it is human-editable.\n */\n async update(id: string, data: object): Promise<void> {\n await this.client.updateFlowDefinition(\n id,\n { flow_definition: data as UpdateFlowDefinitionBodyFlowDefinition },\n { project_id: this.projectId },\n );\n }\n\n async delete(id: string): Promise<void> {\n await this.client.deleteFlowDefinition(id, { project_id: this.projectId });\n }\n\n /**\n * `GET /flow_definitions/:id` returns a detail envelope with metadata\n * (`id`, `project_id`, `created_at`, `updated_at`) plus `flow_definition`.\n * Return only `flow_definition` so diffs compare with the on-disk bare body.\n */\n async fetch(id: string): Promise<object> {\n const envelope = (await this.client.getFlowDefinition(\n id,\n { project_id: this.projectId },\n )) as GetFlowDefinition200;\n\n return envelope.flow_definition as object;\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type { ResourceEntry, ZitadelState } from \"./types.js\";\n\n/**\n * Read and parse `.zitadel/state.json`. Throws if the file is\n * missing or malformed; callers run `zitadel setup` first to bring\n * the file into existence.\n */\nexport async function readState(cwd: string): Promise<ZitadelState> {\n const raw = await readFile(join(cwd, \".zitadel/state.json\"), \"utf8\");\n return JSON.parse(raw) as ZitadelState;\n}\n\n/**\n * Merge an entry into the state file under `key`, preserving any\n * fields the caller did not override. Reads the file, writes it back\n * with sorted keys disabled (state is engine-managed, not human-\n * authored, so deterministic ordering isn't required here).\n */\nexport async function updateState(\n cwd: string,\n key: string,\n entry: ResourceEntry,\n): Promise<void> {\n const current = await readState(cwd);\n const updated: ZitadelState = {\n ...current,\n resources: {\n ...current.resources,\n [key]: { ...current.resources[key], ...entry },\n },\n };\n await writeFile(join(cwd, \".zitadel/state.json\"), JSON.stringify(updated, null, 2));\n}\n\n/**\n * Remove an entry from the state file. No-op if the key is absent.\n */\nexport async function removeFromState(cwd: string, key: string): Promise<void> {\n const current = await readState(cwd);\n const { [key]: _removed, ...rest } = current.resources;\n const updated: ZitadelState = { ...current, resources: rest };\n await writeFile(join(cwd, \".zitadel/state.json\"), JSON.stringify(updated, null, 2));\n}\n","import { createHash } from \"node:crypto\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { consola } from \"consola\";\n\nimport { FLOWS_DIR } from \"../flows\";\nimport { readState, removeFromState, updateState } from \"./state.js\";\nimport type { ResourceEntry, ResourceSyncer, SyncAction } from \"./types.js\";\n\n/**\n * Compute the sync plan for `cwd` against the state file and (when\n * `fetchOld` is true) the platform API. The plan is read-only: it\n * decides what create/update/revise/delete operations need to happen but\n * performs none of them. Pass it to {@link runSyncLoop} to execute.\n *\n * Validates every on-disk file (via `syncer.validate`) before planning any\n * work — a single malformed schema or flow aborts the whole run with\n * `E_VALIDATION` before any platform mutation. Both `plan` and `apply`\n * reach this code path.\n *\n * Bearer auth + base URL live in the api package's runtime registries\n * (`runtime/{auth,base-url}`). Callers set them once at command boot;\n * the sync engine doesn't carry a client.\n *\n * @param cwd - Project root.\n * @param syncers - Per-resource adapters. Order is preserved in the output.\n * @param fetchOld - When true, the planner fetches each delete/update target\n * from the platform to populate `oldContent` for diff rendering.\n */\nexport async function buildSyncPlan(\n cwd: string,\n syncers: ReadonlyArray<ResourceSyncer>,\n fetchOld = false,\n): Promise<ReadonlyArray<SyncAction>> {\n const state = await readState(cwd);\n const actions: SyncAction[] = [];\n\n // Walk local flow files once, up front: revisioned schemas need to name every\n // flow whose `user_schema` currently pins the previous revision, so the CLI\n // can surface a re-pin hint after the new revision is published.\n const localFlows = await readLocalFlowUserSchemas(cwd);\n\n for (const syncer of syncers) {\n const dirPath = join(cwd, syncer.directory);\n consola.debug(`scanning ${syncer.directory}`);\n const onDisk = await readJsonDir(dirPath);\n\n for (const content of onDisk.values()) {\n syncer.validate(content);\n }\n\n for (const [filePath, entry] of Object.entries(state.resources)) {\n if (!filePath.startsWith(syncer.directory)) {\n continue;\n }\n if (onDisk.has(join(cwd, filePath)) || !entry.id) {\n continue;\n }\n\n let oldContent: object | null = null;\n if (fetchOld && syncer.fetch) {\n try {\n oldContent = await syncer.fetch(entry.id);\n } catch (err) {\n consola.debug(`fetch ${syncer.kind} ${entry.id} failed:`, err);\n }\n }\n actions.push({ kind: \"delete\", path: filePath, syncer, id: entry.id, oldContent });\n }\n\n for (const [absPath, content] of onDisk.entries()) {\n const relPath = absPath.slice(cwd.length + 1);\n const entry = state.resources[relPath];\n const hash = hashResourceContent(content);\n\n if (!entry?.id) {\n actions.push({ kind: \"create\", path: relPath, syncer, content, hash });\n continue;\n }\n\n if (entry.hash === hash) {\n actions.push({ kind: \"skip\", path: relPath, reason: \"no-change\" });\n continue;\n }\n\n if (syncer.revisioned) {\n const oldContent = await fetchOldIfAsked(syncer, entry.id, fetchOld);\n actions.push({\n kind: \"revise\",\n path: relPath,\n syncer,\n content,\n hash,\n previousId: entry.id,\n oldContent,\n affectedPaths: findFlowsPinnedTo(entry.id, localFlows),\n });\n continue;\n }\n\n if (!syncer.mutable) {\n actions.push({ kind: \"skip\", path: relPath, reason: \"immutable\" });\n continue;\n }\n\n const oldContent = await fetchOldIfAsked(syncer, entry.id, fetchOld);\n actions.push({\n kind: \"update\",\n path: relPath,\n syncer,\n id: entry.id,\n content,\n hash,\n oldContent,\n });\n }\n }\n\n return actions;\n}\n\n/**\n * Execute every action returned by {@link buildSyncPlan} against the\n * platform. Updates the local state file (`.zitadel/state.json`) as\n * each action completes so an interrupted run can resume.\n *\n * The platform target (base URL + bearer auth) lives in the api\n * package's runtime registries; callers set them before invoking this.\n *\n * @param cwd - Project root.\n * @param syncers - Per-resource adapters; same list passed to\n * `buildSyncPlan`.\n */\nexport async function runSyncLoop(\n cwd: string,\n syncers: ReadonlyArray<ResourceSyncer>,\n): Promise<void> {\n const actions = await buildSyncPlan(cwd, syncers);\n\n for (const action of actions) {\n switch (action.kind) {\n case \"create\": {\n const id = await action.syncer.create(action.content);\n const entry: ResourceEntry = { id, hash: action.hash };\n await updateState(cwd, action.path, entry);\n consola.info(\n `Created a new ${action.syncer.kind} on Zitadel from ${action.path} (id ${id})`,\n );\n break;\n }\n case \"revise\": {\n const id = await action.syncer.create(action.content);\n const entry: ResourceEntry = { id, hash: action.hash };\n await updateState(cwd, action.path, entry);\n consola.info(\n `Published a new ${action.syncer.kind} revision on Zitadel from ${action.path} (id ${id})`,\n );\n if (action.affectedPaths.length > 0) {\n consola.warn(\n `New ${action.syncer.kind} revision ${id}. ` +\n `Update user_schema in these flow definitions to adopt it:\\n` +\n action.affectedPaths.map((path) => ` - ${path}`).join(\"\\n\"),\n );\n }\n break;\n }\n case \"update\": {\n await action.syncer.update(action.id, action.content);\n await updateState(cwd, action.path, { hash: action.hash });\n consola.info(`Updated the ${action.syncer.kind} on Zitadel from ${action.path}`);\n break;\n }\n case \"delete\": {\n await action.syncer.delete(action.id);\n await removeFromState(cwd, action.path);\n consola.info(\n `Deleted the ${action.syncer.kind} on Zitadel because ${action.path} was removed locally`,\n );\n break;\n }\n case \"skip\": {\n consola.debug(`Skipped ${action.path} (${action.reason})`);\n break;\n }\n }\n }\n}\n\nasync function fetchOldIfAsked(\n syncer: ResourceSyncer,\n id: string,\n fetchOld: boolean,\n): Promise<object | null> {\n if (!fetchOld || !syncer.fetch) {\n return null;\n }\n try {\n return await syncer.fetch(id);\n } catch (err) {\n consola.debug(`fetch ${syncer.kind} ${id} failed:`, err);\n return null;\n }\n}\n\nasync function readJsonDir(dirPath: string): Promise<Map<string, object>> {\n const result = new Map<string, object>();\n let entries: string[];\n try {\n entries = await readdir(dirPath);\n } catch (err) {\n if (typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\") {\n return result;\n }\n throw err;\n }\n for (const entry of entries.filter((e) => e.endsWith(\".json\"))) {\n const filePath = join(dirPath, entry);\n const raw = await readFile(filePath, \"utf8\");\n result.set(filePath, JSON.parse(raw) as object);\n }\n return result;\n}\n\n/**\n * Walk `.zitadel/flows/*.json` once and return each flow's `user_schema` value\n * keyed by project-root-relative path. A flow file without a `user_schema` (or\n * with a non-string one) is skipped: it does not pin a schema revision, so it\n * cannot be affected by one.\n */\nasync function readLocalFlowUserSchemas(cwd: string): Promise<Map<string, string>> {\n const result = new Map<string, string>();\n const flows = await readJsonDir(join(cwd, FLOWS_DIR));\n for (const [absPath, content] of flows.entries()) {\n const relPath = absPath.slice(cwd.length + 1);\n if (\n typeof content === \"object\" &&\n content !== null &&\n \"user_schema\" in content &&\n typeof (content as { user_schema: unknown }).user_schema === \"string\"\n ) {\n result.set(relPath, (content as { user_schema: string }).user_schema);\n }\n }\n return result;\n}\n\nfunction findFlowsPinnedTo(\n previousId: string,\n localFlows: Map<string, string>,\n): ReadonlyArray<string> {\n const affected: string[] = [];\n for (const [relPath, ref] of localFlows.entries()) {\n if (ref === previousId) {\n affected.push(relPath);\n }\n }\n return affected;\n}\n\nexport function hashResourceContent(data: object): string {\n return createHash(\"sha256\").update(JSON.stringify(data)).digest(\"hex\");\n}\n","import type { SyncAction, SyncPlanSummary } from \"./types.js\";\n\n/**\n * Count the non-`skip` actions in a {@link buildSyncPlan} result. Pure; the\n * single source of truth for the plan counts shared by the `plan` /\n * `apply --dry-run` JSON payload and {@link renderPlan}'s summary line.\n */\nexport function summarizePlan(actions: ReadonlyArray<SyncAction>): SyncPlanSummary {\n const active = actions.filter((a) => a.kind !== \"skip\");\n return {\n creates: active.filter((a) => a.kind === \"create\").length,\n updates: active.filter((a) => a.kind === \"update\").length,\n revisions: active.filter((a) => a.kind === \"revise\").length,\n deletes: active.filter((a) => a.kind === \"delete\").length,\n total: active.length,\n };\n}\n\n/**\n * Render a {@link buildSyncPlan} result as a human-readable Terraform-style\n * plan. TTY-aware: colors and bold are emitted only when `tty` is true.\n * Returns the empty-state message when every action is `skip`.\n *\n * @param actions - The action list produced by `buildSyncPlan`. Read-only;\n * the function never mutates the input.\n * @param tty - True when stdout is a TTY; controls ANSI emission.\n */\nexport function renderPlan(actions: ReadonlyArray<SyncAction>, tty: boolean): string {\n const active = actions.filter((a) => a.kind !== \"skip\");\n\n if (active.length === 0) {\n return paint(\n \"No changes. Your Zitadel configuration matches the current state.\",\n A.bold,\n tty,\n );\n }\n\n const out: string[] = [];\n out.push(paint(\"Zitadel will perform the following actions:\", A.bold, tty));\n\n for (const action of active) {\n out.push(\"\");\n out.push(...renderBlock(action, tty));\n }\n\n out.push(\"\");\n\n const { creates, updates, revisions, deletes } = summarizePlan(actions);\n\n const parts: string[] = [];\n if (creates > 0) {\n parts.push(`${creates} to add`);\n }\n if (updates > 0) {\n parts.push(`${updates} to change`);\n }\n if (revisions > 0) {\n parts.push(`${revisions} new revision${revisions === 1 ? \"\" : \"s\"}`);\n }\n if (deletes > 0) {\n parts.push(`${deletes} to destroy`);\n }\n\n out.push(paint(`Plan: ${parts.join(\", \")}.`, A.bold, tty));\n return out.join(\"\\n\");\n}\n\nconst A = {\n reset: \"\\x1b[0m\",\n bold: \"\\x1b[1m\",\n green: \"\\x1b[32m\",\n red: \"\\x1b[31m\",\n yellow: \"\\x1b[33m\",\n} as const;\n\nfunction paint(text: string, code: string, tty: boolean): string {\n return tty ? `${code}${text}${A.reset}` : text;\n}\n\nfunction isPrimitive(v: unknown): v is string | number | boolean | null {\n return v === null || typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\";\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nconst KNOWN_AFTER_APPLY = \"(known after apply)\";\n\nfunction escapeString(s: string): string {\n return s\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\");\n}\n\nfunction fmtPrimitive(v: string | number | boolean | null): string {\n if (v === null) {\n return \"null\";\n }\n if (typeof v === \"string\" && v === KNOWN_AFTER_APPLY) {\n return KNOWN_AFTER_APPLY;\n }\n if (typeof v === \"string\") {\n return `\"${escapeString(v)}\"`;\n }\n return String(v);\n}\n\n/**\n * Indentation contract (matches Terraform exactly):\n * prefixCol = column index of the +/-/~ character\n * field content starts at prefixCol + 2 (one space gap after prefix)\n * nested object/array content: prefixCol + 4 for the child prefixCol\n * closing } or ] : prefixCol + 2 columns of plain spaces, no prefix\n */\ntype ChangePrefix = \"+\" | \"-\" | \"~\" | \" \";\n\nfunction prefixAnsi(p: ChangePrefix): string {\n if (p === \"+\") {\n return A.green;\n }\n if (p === \"-\") {\n return A.red;\n }\n if (p === \"~\") {\n return A.yellow;\n }\n return \"\";\n}\n\ninterface RenderCtx {\n tty: boolean;\n deleteMode: boolean;\n}\n\nfunction renderFields(\n obj: Record<string, unknown>,\n prefix: ChangePrefix,\n prefixCol: number,\n ctx: RenderCtx,\n lines: string[],\n): void {\n const pad = \" \".repeat(prefixCol);\n const ansi = prefixAnsi(prefix);\n const col = (s: string) => paint(s, ansi, ctx.tty);\n\n const keys = Object.keys(obj).sort();\n const maxLen = keys.reduce((m, k) => Math.max(m, k.length), 0);\n\n for (const key of keys) {\n const val = obj[key];\n const pk = key.padEnd(maxLen);\n\n if (isPrimitive(val)) {\n const formatted = fmtPrimitive(val);\n const suffix = ctx.deleteMode ? \" -> null\" : \"\";\n lines.push(col(`${pad}${prefix} ${pk} = ${formatted}${suffix}`));\n } else if (Array.isArray(val)) {\n if (val.length === 0) {\n lines.push(col(`${pad}${prefix} ${pk} = []`));\n } else {\n lines.push(col(`${pad}${prefix} ${pk} = [`));\n renderArrayItems(val, prefix, prefixCol + 4, ctx, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}]`));\n }\n } else if (isPlainObject(val)) {\n if (Object.keys(val).length === 0) {\n lines.push(col(`${pad}${prefix} ${pk} = {}`));\n } else {\n lines.push(col(`${pad}${prefix} ${pk} = {`));\n renderFields(val, prefix, prefixCol + 4, ctx, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}}`));\n }\n }\n }\n}\n\n/**\n * Renders the items of an array. Unlike {@link renderFields}, primitive\n * elements never get a trailing ` -> null` suffix even under `deleteMode` —\n * Terraform only annotates scalar object-field removals that way, not array\n * items.\n */\nfunction renderArrayItems(\n arr: ReadonlyArray<unknown>,\n prefix: ChangePrefix,\n prefixCol: number,\n ctx: RenderCtx,\n lines: string[],\n): void {\n const pad = \" \".repeat(prefixCol);\n const ansi = prefixAnsi(prefix);\n const col = (s: string) => paint(s, ansi, ctx.tty);\n\n for (const item of arr) {\n if (isPrimitive(item)) {\n const formatted = fmtPrimitive(item);\n lines.push(col(`${pad}${prefix} ${formatted},`));\n } else if (Array.isArray(item)) {\n if (item.length === 0) {\n lines.push(col(`${pad}${prefix} [],`));\n } else {\n lines.push(col(`${pad}${prefix} [`));\n renderArrayItems(item, prefix, prefixCol + 4, ctx, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}],`));\n }\n } else if (isPlainObject(item)) {\n if (Object.keys(item).length === 0) {\n lines.push(col(`${pad}${prefix} {},`));\n } else {\n lines.push(col(`${pad}${prefix} {`));\n renderFields(item, prefix, prefixCol + 4, ctx, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}},`));\n }\n }\n }\n}\n\n/**\n * Walks both old and new objects, emitting Terraform-style change lines.\n * Returns true if any actual change line (+ / - / ~) was emitted.\n *\n * Edge cases:\n * - Changed arrays render as a full remove + full add (no LCS diff).\n * - Nested objects recurse, and the outer key is only marked `~` if a child\n * actually changed; unchanged children render with the neutral prefix.\n * - A value whose type changed (e.g. string → object) also renders as a\n * remove + add pair.\n */\nfunction renderDiff(\n oldObj: Record<string, unknown>,\n newObj: Record<string, unknown>,\n prefixCol: number,\n tty: boolean,\n lines: string[],\n): boolean {\n const allKeys = [...new Set([...Object.keys(oldObj), ...Object.keys(newObj)])].sort();\n const maxLen = allKeys.reduce((m, k) => Math.max(m, k.length), 0);\n const pad = \" \".repeat(prefixCol);\n let hasChanges = false;\n\n for (const key of allKeys) {\n const pk = key.padEnd(maxLen);\n const hasOld = Object.prototype.hasOwnProperty.call(oldObj, key);\n const hasNew = Object.prototype.hasOwnProperty.call(newObj, key);\n const oldVal = oldObj[key];\n const newVal = newObj[key];\n\n if (!hasOld) {\n hasChanges = true;\n const col = (s: string) => paint(s, A.green, tty);\n if (isPrimitive(newVal)) {\n lines.push(col(`${pad}+ ${pk} = ${fmtPrimitive(newVal)}`));\n } else if (Array.isArray(newVal)) {\n lines.push(col(`${pad}+ ${pk} = [`));\n renderArrayItems(newVal, \"+\", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}]`));\n } else if (isPlainObject(newVal)) {\n lines.push(col(`${pad}+ ${pk} = {`));\n renderFields(newVal, \"+\", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}}`));\n }\n } else if (!hasNew) {\n hasChanges = true;\n const col = (s: string) => paint(s, A.red, tty);\n if (isPrimitive(oldVal)) {\n lines.push(col(`${pad}- ${pk} = ${fmtPrimitive(oldVal)} -> null`));\n } else if (Array.isArray(oldVal)) {\n lines.push(col(`${pad}- ${pk} = [`));\n renderArrayItems(oldVal, \"-\", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}]`));\n } else if (isPlainObject(oldVal)) {\n lines.push(col(`${pad}- ${pk} = {`));\n renderFields(oldVal, \"-\", prefixCol + 4, { tty, deleteMode: true }, lines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}}`));\n }\n } else if (isPrimitive(oldVal) && isPrimitive(newVal)) {\n if (oldVal === newVal) {\n lines.push(`${pad} ${pk} = ${fmtPrimitive(newVal)}`);\n } else {\n hasChanges = true;\n const col = (s: string) => paint(s, A.yellow, tty);\n lines.push(col(`${pad}~ ${pk} = ${fmtPrimitive(oldVal)} -> ${fmtPrimitive(newVal)}`));\n }\n } else if (Array.isArray(oldVal) && Array.isArray(newVal)) {\n if (JSON.stringify(oldVal) === JSON.stringify(newVal)) {\n if (newVal.length === 0) {\n lines.push(`${pad} ${pk} = []`);\n } else {\n lines.push(`${pad} ${pk} = [`);\n renderArrayItems(newVal, \" \", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(`${\" \".repeat(prefixCol + 2)}]`);\n }\n } else {\n hasChanges = true;\n const colR = (s: string) => paint(s, A.red, tty);\n const colA = (s: string) => paint(s, A.green, tty);\n if (oldVal.length === 0) {\n lines.push(colR(`${pad}- ${pk} = []`));\n } else {\n lines.push(colR(`${pad}- ${pk} = [`));\n renderArrayItems(oldVal, \"-\", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(colR(`${\" \".repeat(prefixCol + 2)}]`));\n }\n if (newVal.length === 0) {\n lines.push(colA(`${pad}+ ${pk} = []`));\n } else {\n lines.push(colA(`${pad}+ ${pk} = [`));\n renderArrayItems(newVal, \"+\", prefixCol + 4, { tty, deleteMode: false }, lines);\n lines.push(colA(`${\" \".repeat(prefixCol + 2)}]`));\n }\n }\n } else if (isPlainObject(oldVal) && isPlainObject(newVal)) {\n const childLines: string[] = [];\n const childHasChanges = renderDiff(oldVal, newVal, prefixCol + 4, tty, childLines);\n if (childHasChanges) {\n hasChanges = true;\n const col = (s: string) => paint(s, A.yellow, tty);\n lines.push(col(`${pad}~ ${pk} = {`));\n lines.push(...childLines);\n lines.push(col(`${\" \".repeat(prefixCol + 2)}}`));\n } else if (childLines.length > 0) {\n lines.push(`${pad} ${pk} = {`);\n lines.push(...childLines);\n lines.push(`${\" \".repeat(prefixCol + 2)}}`);\n } else {\n lines.push(`${pad} ${pk} = {}`);\n }\n } else {\n hasChanges = true;\n const colR = (s: string) => paint(s, A.red, tty);\n const colA = (s: string) => paint(s, A.green, tty);\n if (isPrimitive(oldVal)) {\n lines.push(colR(`${pad}- ${pk} = ${fmtPrimitive(oldVal)} -> null`));\n }\n if (isPrimitive(newVal)) {\n lines.push(colA(`${pad}+ ${pk} = ${fmtPrimitive(newVal)}`));\n }\n }\n }\n\n return hasChanges;\n}\n\n/**\n * Column layout (matches Terraform's per-block format):\n * BLOCK_COL = 2 — where the +/-/~ sits on the resource opening line\n * FIELD_COL = 6 — where the +/-/~ sits on first-level field lines\n * closing } — at BLOCK_COL + 2 = 4, no prefix\n */\nconst BLOCK_COL = 2;\nconst FIELD_COL = 6;\n\nfunction resourceName(path: string): string {\n return path.split(\"/\").pop() ?? path;\n}\n\n/**\n * Renders one Terraform-style resource block for a single `SyncAction`.\n *\n * Per-case notes:\n * - **create**: a synthetic `id = (known after apply)` is injected into the\n * rendered fields so it sorts alphabetically alongside the real keys.\n * - **delete**: when `oldContent` is null (the fetch failed), the body\n * collapses to a single `- id = \"<id>\" -> null` line.\n * - **update**: when `oldContent` is null (no read endpoint for this\n * resource kind), the field diff is replaced with a placeholder\n * \"field diff unavailable\" line.\n * - **skip**: omitted from the output entirely, matching Terraform's\n * default of not showing no-change resources.\n */\nfunction renderBlock(action: SyncAction, tty: boolean): string[] {\n const lines: string[] = [];\n const blkPad = \" \".repeat(BLOCK_COL);\n const closePad = \" \".repeat(BLOCK_COL + 2);\n\n switch (action.kind) {\n case \"create\": {\n const header = `${blkPad}# ${action.path} will be created`;\n const opening = `${blkPad}+ resource \"${action.syncer.kind}\" \"${resourceName(action.path)}\" {`;\n lines.push(paint(header, A.bold, tty));\n lines.push(paint(opening, A.green, tty));\n\n const display: Record<string, unknown> = {\n id: KNOWN_AFTER_APPLY,\n ...(action.content as Record<string, unknown>),\n };\n renderFields(display, \"+\", FIELD_COL, { tty, deleteMode: false }, lines);\n lines.push(`${closePad}}`);\n break;\n }\n\n case \"delete\": {\n const header = `${blkPad}# ${action.path} will be destroyed`;\n const opening = `${blkPad}- resource \"${action.syncer.kind}\" \"${resourceName(action.path)}\" {`;\n lines.push(paint(header, A.bold, tty));\n lines.push(paint(opening, A.red, tty));\n\n if (action.oldContent) {\n const display: Record<string, unknown> = {\n id: action.id,\n ...(action.oldContent as Record<string, unknown>),\n };\n renderFields(display, \"-\", FIELD_COL, { tty, deleteMode: true }, lines);\n } else {\n lines.push(paint(`${\" \".repeat(FIELD_COL)}- id = \"${action.id}\" -> null`, A.red, tty));\n }\n lines.push(`${closePad}}`);\n break;\n }\n\n case \"update\": {\n const header = `${blkPad}# ${action.path} will be updated in-place`;\n const opening = `${blkPad}~ resource \"${action.syncer.kind}\" \"${resourceName(action.path)}\" {`;\n lines.push(paint(header, A.bold, tty));\n lines.push(paint(opening, A.yellow, tty));\n\n if (action.oldContent) {\n renderDiff(\n action.oldContent as Record<string, unknown>,\n action.content as Record<string, unknown>,\n FIELD_COL,\n tty,\n lines,\n );\n } else {\n lines.push(\n `${\" \".repeat(FIELD_COL)} # (field diff unavailable — no read endpoint for ${action.syncer.kind})`,\n );\n }\n lines.push(`${closePad}}`);\n break;\n }\n\n case \"revise\": {\n const header = `${blkPad}# ${action.path} will publish a new revision`;\n const opening = `${blkPad}~ resource \"${action.syncer.kind}\" \"${resourceName(action.path)}\" {`;\n lines.push(paint(header, A.bold, tty));\n lines.push(paint(opening, A.yellow, tty));\n\n if (action.oldContent) {\n const oldWithId: Record<string, unknown> = {\n id: action.previousId,\n ...(action.oldContent as Record<string, unknown>),\n };\n const newWithId: Record<string, unknown> = {\n id: KNOWN_AFTER_APPLY,\n ...(action.content as Record<string, unknown>),\n };\n renderDiff(oldWithId, newWithId, FIELD_COL, tty, lines);\n } else {\n lines.push(\n `${\" \".repeat(FIELD_COL)} # (field diff unavailable — no read endpoint for ${action.syncer.kind})`,\n );\n }\n lines.push(`${closePad}}`);\n if (action.affectedPaths.length > 0) {\n lines.push(\n paint(\n `${blkPad}# after apply, update user_schema in these flow definitions:`,\n A.yellow,\n tty,\n ),\n );\n for (const path of action.affectedPaths) {\n lines.push(paint(`${blkPad}# - ${path}`, A.yellow, tty));\n }\n }\n break;\n }\n\n case \"skip\":\n break;\n }\n\n return lines;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA,SAAgB,YAAY,OAA0B;CACpD,MAAM,uBAAO,IAAI,KAAa;CAC9B,MAAM,SAAS,SAAwB;AACrC,MAAI,OAAO,SAAS,SAClB,MAAK,MAAM,SAAS,KAAK,SAAS,kCAAkC,EAAE;GACpE,MAAM,MAAM,MAAM;AAClB,OAAI,IACF,MAAK,IAAI,IAAI;;WAGR,MAAM,QAAQ,KAAK,CAC5B,MAAK,QAAQ,MAAM;WACV,SAAS,KAAK,CACvB,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,CAC7C,KAAI,IAAI,SAAS,OAAO,IAAI,OAAO,UAAU,YAAY,2BAA2B,KAAK,MAAM,CAC7F,MAAK,IAAI,MAAM;MAEf,OAAM,MAAM;;AAKpB,OAAM,MAAM;AACZ,QAAO,CAAC,GAAG,KAAK,CAAC,MAAM;;;;;;;;;;;ACAzB,MAAa,YAAY;;;;;;;;;;;ACLzB,SAAgB,YAA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,IAAI,CAAC;AAEzC,OAAI,OAAO,WAST,YAAW;IAPT,IAAI,OAAO;IACX,GAAI,OAAO;IAMO,EAAE;IAHpB,IAAI;IACJ,GAAI,OAAO;IAEkB,EAAE,WAAW,KAAK,MAAM;OAEvD,OAAM,KACJ,GAAG,IAAI,OAAO,UAAU,CAAC,qDAAqD,OAAO,OAAO,KAAK,GAClG;AAEH,SAAM,KAAK,GAAG,SAAS,GAAG;AAC1B,OAAI,OAAO,cAAc,SAAS,GAAG;AACnC,UAAM,KACJ,MACE,GAAG,OAAO,+DACV,EAAE,QACF,IACD,CACF;AACD,SAAK,MAAM,QAAQ,OAAO,cACxB,OAAM,KAAK,MAAM,GAAG,OAAO,QAAQ,QAAQ,EAAE,QAAQ,IAAI,CAAC;;AAG9D;;EAGF,KAAK,OACH;;AAGJ,QAAO"}
@@ -0,0 +1,13 @@
1
+ //#region src/lib/user-schema/index.ts
2
+ /**
3
+ * Relative directory (from the project root) where local user-schema
4
+ * files live. Owned here so callers (`commands/*`, `sync/syncers.ts`)
5
+ * and tests share a single source of truth for the path; the runtime
6
+ * never depends on it directly because `lib/user-schema` does not touch
7
+ * the filesystem. The counterpart of `lib/flows`' `FLOWS_DIR`.
8
+ */
9
+ const SCHEMAS_DIR = ".zitadel/schemas";
10
+ //#endregion
11
+ export { SCHEMAS_DIR as t };
12
+
13
+ //# sourceMappingURL=user-schema-DDz5-lX5.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user-schema-DDz5-lX5.mjs","names":[],"sources":["../src/lib/user-schema/index.ts"],"sourcesContent":["/**\n * Public surface for the user-schema domain. Every caller outside this\n * module imports from here (not from individual files), the same\n * discipline as `lib/flows/`.\n *\n * **Source of truth.** The wire shape lives in\n * `@zitadel/api/generated/model` (orval-generated from the\n * OpenAPI spec). Callers that need the type import `CreateSchemaBody`\n * from there directly; callers that need the runtime validator import\n * the matching Zod schema from\n * `@zitadel/api/generated/endpoints/zitadelNextGen.zod`. This\n * module owns only CLI-specific concerns: the builder, the per-field\n * preset catalog, and the two `DEFAULT_*` URI constants.\n *\n * **Dependency rule.** No upward imports (`commands/`, `sync/`, etc.)\n * and no filesystem I/O. Reading and writing local files is the\n * caller's responsibility, served by `apps/cli/src/lib/json-dir.ts`\n * plus this module's {@link SCHEMAS_DIR} constant.\n */\nexport {\n DEFAULT_USER_META_SCHEMA,\n DEFAULT_USER_SCHEMA_ID,\n buildUserSchema,\n} from \"./build\";\n\n/**\n * Relative directory (from the project root) where local user-schema\n * files live. Owned here so callers (`commands/*`, `sync/syncers.ts`)\n * and tests share a single source of truth for the path; the runtime\n * never depends on it directly because `lib/user-schema` does not touch\n * the filesystem. The counterpart of `lib/flows`' `FLOWS_DIR`.\n */\nexport const SCHEMAS_DIR = \".zitadel/schemas\";\n"],"mappings":";;;;;;;;AAgCA,MAAa,cAAc"}