@installagent/sdk 0.17.0 → 0.18.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.
package/dist/index.d.ts CHANGED
@@ -37,6 +37,7 @@ export { type CreateLoggerOptions, createLogger, type LogFields, type Logger, ty
37
37
  export { applyClientDefaults, clientWorkflowName, DEFAULT_EXECUTION_TIMEOUT_S, DEFAULT_GET_RETRY, DEFAULT_WORKFLOW_SETTINGS, ERROR_WORKFLOW_PLACEHOLDER, IA_ERROR_WORKFLOW_ID, type LintFileResult, type LintFinding, type LintOptions, lintN8nWorkflow, lintWorkflowFiles, WORKFLOW_NAME_PATTERN, } from "./n8n-defaults.js";
38
38
  export { type N8nDraftSelectedBy, type N8nDraftsDiff, type N8nDraftsOptions, type N8nDraftsResult, type N8nDraftWorkflow, n8nDrafts, } from "./n8n-drafts.js";
39
39
  export { type ExtractNodeOutputsOptions, extractNodeOutputs, listN8nExecutions, listNodesRun, type N8nExecutionDetail, type N8nExecutionStatus, type N8nExecutionSummary, type N8nExecutionsInput, type N8nExecutionsOptions, type N8nExecutionsResult, type N8nNodeOutput, unflattenExecutionData, } from "./n8n-executions.js";
40
+ export { type ClientWorkflowExport, type N8nExportItem, type N8nExportOptions, type N8nExportResult, n8nExport, sanitizeClientExport, } from "./n8n-export.js";
40
41
  export { type NewClientOptions, type NewClientResult, newClient, SLUG_PATTERN, } from "./new-client.js";
41
42
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
42
43
  export { defaultOpTitle, type MintImpls, type MintToOpOptions, type MintToOpRequest, type MintToOpResult, mintToOnePassword, } from "./op-store.js";
package/dist/index.js CHANGED
@@ -40,6 +40,7 @@ export { createLogger, redactFields, } from "./log.js";
40
40
  export { applyClientDefaults, clientWorkflowName, DEFAULT_EXECUTION_TIMEOUT_S, DEFAULT_GET_RETRY, DEFAULT_WORKFLOW_SETTINGS, ERROR_WORKFLOW_PLACEHOLDER, IA_ERROR_WORKFLOW_ID, lintN8nWorkflow, lintWorkflowFiles, WORKFLOW_NAME_PATTERN, } from "./n8n-defaults.js";
41
41
  export { n8nDrafts, } from "./n8n-drafts.js";
42
42
  export { extractNodeOutputs, listN8nExecutions, listNodesRun, unflattenExecutionData, } from "./n8n-executions.js";
43
+ export { n8nExport, sanitizeClientExport, } from "./n8n-export.js";
43
44
  export { newClient, SLUG_PATTERN, } from "./new-client.js";
44
45
  export { opInstallCommand, opInstallFix, opIntegrationFix } from "./op-cli.js";
45
46
  export { defaultOpTitle, mintToOnePassword, } from "./op-store.js";
@@ -0,0 +1,75 @@
1
+ import type { ExecFileFn } from "./exec.js";
2
+ import { type N8nDraftWorkflow } from "./n8n-drafts.js";
3
+ export interface ClientWorkflowExport {
4
+ /** The live n8n workflow id: what every drift check joins on. */
5
+ id: string;
6
+ name: string;
7
+ nodes: Array<Record<string, unknown>>;
8
+ connections: Record<string, unknown>;
9
+ settings: Record<string, unknown>;
10
+ }
11
+ /**
12
+ * A raw n8n workflow reduced to a client export. The node strip is the bank's
13
+ * (`sanitizeN8nWorkflow`: credentials and webhook ids removed; pinData,
14
+ * staticData, versions, tags and sharing never copied). Two differences from
15
+ * a bank template: the settings stay the LIVE ones (an export says what runs
16
+ * for this client, error workflow included), and each credential slot comes
17
+ * back as a placeholder so a reader sees which node needs which credential type.
18
+ */
19
+ export declare function sanitizeClientExport(raw: Record<string, unknown>): ClientWorkflowExport;
20
+ export interface N8nExportItem {
21
+ workflowId: string;
22
+ name: string;
23
+ state: N8nDraftWorkflow["state"];
24
+ /** Path in the client repo, for example workflows/acme-triage-reader.json. */
25
+ file: string;
26
+ /** `unchanged` = the file already holds exactly this export. */
27
+ action: "create" | "update" | "unchanged";
28
+ /**
29
+ * How an existing file was found. `name` = the file records no id and is the
30
+ * only export with this workflow name; the new content records the id.
31
+ */
32
+ joinedBy: "id" | "name" | null;
33
+ /** How many credential slots got a placeholder. */
34
+ credentialSlots: number;
35
+ written: boolean;
36
+ /** The workflow could not be read. Nothing was written for it. */
37
+ error?: string;
38
+ }
39
+ export interface N8nExportResult {
40
+ workspaceDir: string;
41
+ generatedAt: string;
42
+ slug: string;
43
+ /** False = a plan only. */
44
+ write: boolean;
45
+ /** By workflow name. */
46
+ items: N8nExportItem[];
47
+ notes: string[];
48
+ }
49
+ export interface N8nExportOptions {
50
+ /** The installagent/ workspace root (contains clients/). */
51
+ workspaceDir?: string;
52
+ /** The client, without the `client-` prefix. */
53
+ slug: string;
54
+ /** Only this workflow id (it must be one of the client's). */
55
+ workflowId?: string;
56
+ /** Write the files. Default false: plan only. */
57
+ write?: boolean;
58
+ /** n8n API base incl. /api/v1; defaults to $N8N_API_URL. */
59
+ baseUrl?: string;
60
+ /** Defaults to $N8N_API_KEY. */
61
+ apiKey?: string;
62
+ env?: NodeJS.ProcessEnv;
63
+ fetchImpl?: typeof fetch;
64
+ /** `git log` (through n8nDrafts). Injectable for tests. */
65
+ execFileImpl?: ExecFileFn;
66
+ now?: () => Date;
67
+ }
68
+ /**
69
+ * Plan (and with `write`, write) the exports of one client's live workflows.
70
+ * The client's workflows are the ones `n8nDrafts` lists (the CLIENT.md
71
+ * n8n_tag, a Builds row, or an export that records the id), archived ones left
72
+ * out. An existing export is found by its recorded id; a file with no id is
73
+ * taken over only when it is the one export with exactly the workflow's name.
74
+ */
75
+ export declare function n8nExport(options: N8nExportOptions): Promise<N8nExportResult>;
@@ -0,0 +1,176 @@
1
+ // `ia n8n export <slug>` — write a client's live n8n workflows into its
2
+ // checkout as reviewed exports.
3
+ //
4
+ // `ia n8n drafts` and `ia client-drift` say which exports are stale, missing
5
+ // or cannot be joined (no recorded id). Until now the fix was a browser
6
+ // download and a hand scrub of credential ids. This is that step as one
7
+ // command, with the two rules the drift checks depend on:
8
+ //
9
+ // 1. THE EXPORT RECORDS ITS LIVE ID (`"id"`), so every later check joins by
10
+ // id and a rename on the instance never reads as a deletion.
11
+ // 2. NO CREDENTIAL ID AND NO CREDENTIAL NAME reaches the file. Each slot
12
+ // keeps its type with a `__SET_IN_N8N__<type>__` placeholder id, the form
13
+ // client-template's repo-lint accepts.
14
+ //
15
+ // It reads n8n (GET only), and it writes ONLY inside clients/client-<slug>/
16
+ // workflows/, and only with `write`. It never commits, never pushes, and
17
+ // never changes anything on the instance. Node parameters are kept as they
18
+ // are (that is the point of an export), and they can hold a client address:
19
+ // a person reads the diff before the commit, as CADENCE.md says.
20
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
21
+ import { writeFile } from "node:fs/promises";
22
+ import { join, resolve } from "node:path";
23
+ import { fetchLiveWorkflows } from "./agent-mirror.js";
24
+ import { N8N_API_KEY_ENV, N8N_API_URL_ENV, N8nAuthError, sanitizeN8nWorkflow, } from "./agent-templates.js";
25
+ import { n8nDrafts } from "./n8n-drafts.js";
26
+ /** A placeholder id that client-template's repo-lint accepts (`PLACEHOLDER_ID`). */
27
+ const credentialPlaceholder = (type) => `__SET_IN_N8N__${type}__`;
28
+ const CREDENTIAL_NAME_PLACEHOLDER = "__SET_IN_N8N__";
29
+ /**
30
+ * A raw n8n workflow reduced to a client export. The node strip is the bank's
31
+ * (`sanitizeN8nWorkflow`: credentials and webhook ids removed; pinData,
32
+ * staticData, versions, tags and sharing never copied). Two differences from
33
+ * a bank template: the settings stay the LIVE ones (an export says what runs
34
+ * for this client, error workflow included), and each credential slot comes
35
+ * back as a placeholder so a reader sees which node needs which credential type.
36
+ */
37
+ export function sanitizeClientExport(raw) {
38
+ const { workflow, strippedCredentials } = sanitizeN8nWorkflow(raw);
39
+ const slotsByNode = new Map();
40
+ for (const { node, type } of strippedCredentials) {
41
+ slotsByNode.set(node, [...(slotsByNode.get(node) ?? []), type]);
42
+ }
43
+ const nodes = workflow.nodes.map((node) => {
44
+ const slots = slotsByNode.get(String(node.name));
45
+ if (!slots)
46
+ return node;
47
+ return {
48
+ ...node,
49
+ credentials: Object.fromEntries(slots.map((type) => [
50
+ type,
51
+ { id: credentialPlaceholder(type), name: CREDENTIAL_NAME_PLACEHOLDER },
52
+ ])),
53
+ };
54
+ });
55
+ const settings = raw.settings && typeof raw.settings === "object"
56
+ ? raw.settings
57
+ : {};
58
+ return {
59
+ id: String(raw.id ?? ""),
60
+ name: workflow.name,
61
+ nodes,
62
+ connections: workflow.connections,
63
+ settings,
64
+ };
65
+ }
66
+ const fileSlug = (name) => name
67
+ .toLowerCase()
68
+ .replace(/[^a-z0-9]+/g, "-")
69
+ .replace(/^-+|-+$/g, "") || "workflow";
70
+ const message = (error) => (error instanceof Error ? error.message : String(error));
71
+ /**
72
+ * Plan (and with `write`, write) the exports of one client's live workflows.
73
+ * The client's workflows are the ones `n8nDrafts` lists (the CLIENT.md
74
+ * n8n_tag, a Builds row, or an export that records the id), archived ones left
75
+ * out. An existing export is found by its recorded id; a file with no id is
76
+ * taken over only when it is the one export with exactly the workflow's name.
77
+ */
78
+ export async function n8nExport(options) {
79
+ const workspaceDir = resolve(options.workspaceDir ?? ".");
80
+ const env = options.env ?? process.env;
81
+ const baseUrl = (options.baseUrl ?? env[N8N_API_URL_ENV])?.replace(/\/+$/, "");
82
+ const apiKey = options.apiKey ?? env[N8N_API_KEY_ENV];
83
+ if (!baseUrl || !apiKey) {
84
+ throw new N8nAuthError(`n8n API not configured — set $${N8N_API_URL_ENV} (incl. /api/v1) and $${N8N_API_KEY_ENV} (1Password).`);
85
+ }
86
+ const fetchImpl = options.fetchImpl ?? fetch;
87
+ const now = (options.now ?? (() => new Date()))();
88
+ const liveWorkflows = await fetchLiveWorkflows({ baseUrl, apiKey, fetchImpl });
89
+ const drafts = await n8nDrafts({
90
+ workspaceDir,
91
+ slug: options.slug,
92
+ liveWorkflows,
93
+ execFileImpl: options.execFileImpl,
94
+ now: () => now,
95
+ });
96
+ const slug = drafts.slug;
97
+ const repoDir = join(workspaceDir, "clients", `client-${slug}`);
98
+ let targets = drafts.workflows.filter((w) => w.state !== "archived");
99
+ if (options.workflowId) {
100
+ targets = targets.filter((w) => w.id === options.workflowId);
101
+ if (targets.length === 0) {
102
+ throw new Error(`"${options.workflowId}" is not one of ${slug}'s workflows (run \`ia n8n drafts ${slug}\` for the list; an archived workflow is not exported).`);
103
+ }
104
+ }
105
+ // A file with no recorded id may be taken over only when its name is unique among them.
106
+ const unjoined = new Map();
107
+ for (const orphan of drafts.diff.orphanExports) {
108
+ if (orphan.reason !== "no-recorded-id")
109
+ continue;
110
+ unjoined.set(orphan.name, [...(unjoined.get(orphan.name) ?? []), orphan.file]);
111
+ }
112
+ const workflowsDir = join(repoDir, "workflows");
113
+ const taken = new Set(existsSync(workflowsDir) ? readdirSync(workflowsDir).map((file) => `workflows/${file}`) : []);
114
+ const items = [];
115
+ for (const target of targets) {
116
+ const byName = unjoined.get(target.name);
117
+ const existing = target.export
118
+ ? { file: target.export.file, joinedBy: "id" }
119
+ : byName?.length === 1
120
+ ? { file: byName[0], joinedBy: "name" }
121
+ : null;
122
+ let file = existing?.file ?? `workflows/${fileSlug(target.name)}.json`;
123
+ if (!existing && taken.has(file))
124
+ file = `workflows/${fileSlug(target.name)}-${target.id}.json`;
125
+ taken.add(file);
126
+ const item = {
127
+ workflowId: target.id,
128
+ name: target.name,
129
+ state: target.state,
130
+ file,
131
+ action: existing ? "update" : "create",
132
+ joinedBy: existing?.joinedBy ?? null,
133
+ credentialSlots: 0,
134
+ written: false,
135
+ };
136
+ items.push(item);
137
+ try {
138
+ const response = await fetchImpl(`${baseUrl}/workflows/${encodeURIComponent(target.id)}`, {
139
+ headers: { "X-N8N-API-KEY": apiKey, accept: "application/json" },
140
+ });
141
+ if (!response.ok)
142
+ throw new Error(`n8n API ${response.status} reading the workflow`);
143
+ const exported = sanitizeClientExport((await response.json()));
144
+ item.credentialSlots = exported.nodes.reduce((sum, node) => sum + Object.keys(node.credentials ?? {}).length, 0);
145
+ const text = `${JSON.stringify(exported, null, 2)}\n`;
146
+ const path = join(repoDir, file);
147
+ if (existing && existsSync(path) && readFileSync(path, "utf8") === text) {
148
+ item.action = "unchanged";
149
+ }
150
+ else if (options.write) {
151
+ await writeFile(path, text);
152
+ item.written = true;
153
+ }
154
+ }
155
+ catch (error) {
156
+ item.error = message(error).split("\n")[0];
157
+ }
158
+ }
159
+ const notes = [
160
+ options.write
161
+ ? "Files were written in workflows/ only. Nothing was committed, and nothing on n8n was changed."
162
+ : "Plan only: nothing was written. Add --write to write the files.",
163
+ "Each export records the live workflow id and has a placeholder for each credential id and name. Node parameters are kept as they are and can hold a client address: read the diff, run `node ci/repo-lint.mjs .`, then commit the export with its other surfaces (CADENCE.md).",
164
+ ];
165
+ if (items.some((item) => item.joinedBy === "name")) {
166
+ notes.push("Some files were found by name: they record no id, and each is the only export with that workflow name. Check that each one is the same workflow before you commit.");
167
+ }
168
+ return {
169
+ workspaceDir,
170
+ generatedAt: now.toISOString(),
171
+ slug,
172
+ write: options.write ?? false,
173
+ items,
174
+ notes,
175
+ };
176
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@installagent/sdk",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Install Agent's shared SDK for internal team operations (client repos, n8n workflows, docs search, and more).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",