diff --git a/docs/README.md b/docs/README.md index 3bf7908..ab7bc7c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -111,7 +111,7 @@ edit the command's Short, Long, Example or flag usage and run `make docs`. | [`n8n otel set`](n8n_otel_set.md) | Fully replace OpenTelemetry settings | | [`n8n otel test-trace`](n8n_otel_test-trace.md) | Send one test span to an OTLP collector | | [`n8n otel`](n8n_otel.md) | Manage OpenTelemetry tracing settings | -| [`n8n package export`](n8n_package_export.md) | Export workflows, folders, or projects as an n8n package (beta) | +| [`n8n package export`](n8n_package_export.md) | Export agents, workflows, folders, or projects as an n8n package (beta) | | [`n8n package import`](n8n_package_import.md) | Import an n8n package into a project (beta) | | [`n8n package`](n8n_package.md) | Export and import n8n packages (beta) | | [`n8n project create`](n8n_project_create.md) | Create a project | diff --git a/docs/n8n_package.md b/docs/n8n_package.md index 14f858e..d9fd1fc 100644 --- a/docs/n8n_package.md +++ b/docs/n8n_package.md @@ -4,7 +4,7 @@ Export and import n8n packages (beta) ### Synopsis -Move workflows, folders, and projects between instances as gzipped tar +Move agents, workflows, folders, and projects between instances as gzipped tar packages (.n8np). Start with 'export' to write a package file from this instance, then 'import' to read one back into a project. @@ -36,6 +36,6 @@ n8n package [flags] ### SEE ALSO * [n8n](n8n.md) - Command-line client for the n8n API -* [n8n package export](n8n_package_export.md) - Export workflows, folders, or projects as an n8n package (beta) +* [n8n package export](n8n_package_export.md) - Export agents, workflows, folders, or projects as an n8n package (beta) * [n8n package import](n8n_package_import.md) - Import an n8n package into a project (beta) diff --git a/docs/n8n_package_export.md b/docs/n8n_package_export.md index 020c793..056263e 100644 --- a/docs/n8n_package_export.md +++ b/docs/n8n_package_export.md @@ -1,21 +1,23 @@ ## n8n package export -Export workflows, folders, or projects as an n8n package (beta) +Export agents, workflows, folders, or projects as an n8n package (beta) ### Synopsis -Export workflows and/or folders, or whole projects, as a gzipped tar -archive (.n8np) streamed to a local file. Pass --workflow-id and/or ---folder-id for loose workflows and folders, or --project-id for whole -projects, but not both groups in the same request; at least one ID is -required. Each exported folder includes its nested folders. +Export agents, workflows, and/or folders, or whole projects, as a gzipped +tar archive (.n8np) streamed to a local file. Pass --agent-id, +--workflow-id, and/or --folder-id for loose entities, or --project-id for +whole projects, but not both groups in the same request; at least one ID +is required. Each exported folder includes its nested folders, and whole +projects include their agents when the agents module is enabled. Beta: breaking changes may still occur without a major version bump. -Requires the licensed Packages feature: workflow and folder exports need -workflow:export, project exports need project:export, and exports that -reference variables with values included also need variable:list. -Statically referenced sub-workflows must be included or the export is -rejected under the default missing-dependency policy. The archive may +Requires the licensed Packages feature: agent exports need agent:export +and the agents module, workflow and folder exports need workflow:export, +project exports need project:export, and exports that reference +variables with values included also need variable:list. Workflow and +agent dependencies outside the selection must be included or the export +is rejected under the default --dependency-policy fail. The archive may bundle variable values and credential expressions, so it is written with owner-only file permissions and the destination file is overwritten. @@ -35,28 +37,30 @@ n8n package export [flags] ``` n8n package export --workflow-id 2tUt1wbLX592XDdX --out workflows.n8np n8n package export --workflow-id a --folder-id 9xKp2mNqRzAbCdEf --out mixed.n8np - n8n package export --project-id Ox8O54VQrmBrb4qL --out project.n8np --output json + n8n package export --project-id Ox8O54VQrmBrb4qL --dependency-policy include-in-package --out project.n8np --output json + n8n package export --agent-id uT9LdQx7rK2MvB4f --version-policy prefer-published --out agent.n8np n8n package export --input selection.json --out workflows.n8np ``` ### Options ``` - --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') - --credential-export-policy string credential data handling: expression-values-only or no-values; literal values never travel (default: server default expression-values-only) - --folder-id stringArray folder to include with nested folders, repeatable up to 300 (cannot combine with --project-id or --input) - -h, --help help for export - --include-archived include archived workflows in folder and project exports; listed workflows always export (default: false) - --include-tags bundle workflow tags, else no tag files or references (default: true) (default true) - --include-variable-values bundle referenced variable values, else names only (default: true) (default true) - --input string export selection as JSON: a file path, or - for stdin (cannot combine with selection or policy flags; maximum 1 MiB) - --missing-workflow-dependency-policy string missing static sub-workflow handling: fail, reference-only, or include-in-package (default: server default fail) - --out string local destination for the .n8np archive: a file path, or - for stdout raw bytes (required) - --output string summary format: text or json (JSON is the counts, filename, byte size, and local file) (default "text") - --project-id stringArray project to include, repeatable (cannot combine with --workflow-id, --folder-id, or --input) - --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) - --workflow-id stringArray workflow to include, repeatable up to 300 (cannot combine with --project-id or --input) - --workflow-version-policy string which workflow version travels: published-strict, prefer-published, ignore-unpublished, or latest (default: server default latest) + --agent-id stringArray agent to include, repeatable up to 300; needs the agents module (cannot combine with --project-id or --input) + --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') + --credential-export-policy string credential data handling: expression-values-only or no-values; literal values never travel (default: server default expression-values-only) + --dependency-policy string workflow and agent dependencies outside the selection: fail, reference-only, or include-in-package (default: server default fail) + --folder-id stringArray folder to include with nested folders, repeatable up to 300 (cannot combine with --project-id or --input) + -h, --help help for export + --include-archived include archived workflows in folder and project exports; listed workflows always export (default: false) + --include-tags bundle workflow tags, else no tag files or references (default: true) (default true) + --include-variable-values bundle referenced variable values, else names only (default: true) (default true) + --input string export selection as JSON: a file path, or - for stdin (cannot combine with selection or policy flags; maximum 1 MiB) + --out string local destination for the .n8np archive: a file path, or - for stdout raw bytes (required) + --output string summary format: text or json (JSON is the counts, filename, byte size, and local file) (default "text") + --project-id stringArray project to include with its workflows and agents, repeatable up to 300 (cannot combine with --agent-id, --workflow-id, --folder-id, or --input) + --url string instance URL override, e.g. https://n8n.example.com (falls back to N8N_URL, then the selected context URL) + --version-policy string which workflow and agent version travels: published-strict, prefer-published, ignore-unpublished, or latest (default: server default latest) + --workflow-id stringArray workflow to include, repeatable up to 300 (cannot combine with --project-id or --input) ``` ### SEE ALSO diff --git a/docs/n8n_package_import.md b/docs/n8n_package_import.md index 1adf819..7e001cf 100644 --- a/docs/n8n_package_import.md +++ b/docs/n8n_package_import.md @@ -18,13 +18,17 @@ state (archiving needs workflow:delete), folder overwrite can remove workflows the package does not contain (archive is recoverable, hard-delete also drops executions permanently, so prefer archive), missing credentials become empty stubs unless --credential-missing-mode -must-preexist, and folders, tags, variables, or tables may be created or -overwritten. Interactive runs ask for confirmation and non-interactive -runs require --yes; --file - also requires --yes because stdin cannot -answer. Needs workflow:import plus, depending on the package and the -policies, variable, tag, data-table, folder, and delete scopes, and the -Packages, Variables, and Folders features where the contents require -them. +is must-preexist or create-with-values, --data-table-schema-policy +overwrite permanently drops the values in removed or retyped columns, +and folders, tags, variables, or tables may be created or overwritten. +Interactive runs ask for confirmation and non-interactive runs require +--yes; --file - also requires --yes because stdin cannot answer. +Credentials created from incomplete package data are reported on +stderr and keep their workflows unpublished until completed. Needs +workflow:import plus, depending on the package and the policies, +credential, variable, tag, data-table, folder, and delete scopes, and +the Packages, Variables, and Folders features where the contents +require them. ``` n8n package import [flags] @@ -44,10 +48,10 @@ n8n package import [flags] --bindings string explicit credential bindings as JSON, e.g. '{"credentials":{"pkg-id":"target-id"}}' (default: server default {}) --context string saved context name to use (falls back to N8N_CONTEXT, then the saved current context; see 'n8n config context list') --credential-matching-mode string how package credential references match: id-only, name-and-type, or type-only (default: server default id-only) - --credential-missing-mode string unresolvable credential handling: must-preexist rejects, create-stub creates empty placeholders (default: server default create-stub) + --credential-missing-mode string unresolvable credential handling: must-preexist rejects, create-stub creates empty placeholders, create-with-values seeds them from the package's expression values (needs credential:create; unconfirmed data lands in credentials.incomplete and blocks publishing) (default: server default create-stub) --data-table-matching-mode string data-table matching: by-id, the only mode (default: server default by-id) --data-table-missing-mode string missing data-table handling: create, must-preexist, or do-nothing (default: server default create) - --data-table-schema-policy string matched table schema strictness: keep-existing or fail (default: server default keep-existing) + --data-table-schema-policy string matched table schema handling: keep-existing accepts extra target columns, fail rejects any difference, overwrite reshapes the table to the package and permanently drops values in removed or retyped columns for every workflow using it, overwrite-non-destructive applies the same changes but rejects removals and retypes; rows are kept (default: server default keep-existing) --file string package archive (.n8np) to import: a file path, or - for stdin (required; stdin requires --yes) --folder-conflict-policy string existing folder handling: merge, fail, or overwrite; empty follows --project-conflict-policy on project packages, merge otherwise (default: follow) --folder-id string folder within the target project, from 'n8n folder list PROJECT_ID' (default: the project root) diff --git a/internal/cli/n8n_package.go b/internal/cli/n8n_package.go index aab0d0b..5ba2a7b 100644 --- a/internal/cli/n8n_package.go +++ b/internal/cli/n8n_package.go @@ -6,9 +6,11 @@ import ( "encoding/json" "fmt" "io" + "maps" "net/http" "os" "path/filepath" + "slices" "strings" "text/tabwriter" @@ -27,7 +29,7 @@ func newPackageCommand(opts Options) *cobra.Command { cmd := &cobra.Command{ Use: "package", Short: "Export and import n8n packages (beta)", - Long: "Move workflows, folders, and projects between instances as gzipped tar\n" + + Long: "Move agents, workflows, folders, and projects between instances as gzipped tar\n" + "packages (.n8np). Start with 'export' to write a package file from this\n" + "instance, then 'import' to read one back into a project.\n\n" + "The whole group is beta: breaking changes may still occur without a major\n" + @@ -49,15 +51,25 @@ func newPackageCommand(opts Options) *cobra.Command { return cmd } +// Export flags renamed with the dependencyPolicy and versionPolicy fields. +// The old names stay as hidden, deprecated aliases so scripts keep working. +const ( + packageDependencyPolicyFlag = "dependency-policy" + packageVersionPolicyFlag = "version-policy" + packageLegacyDependencyPolicyFlag = "missing-workflow-dependency-policy" + packageLegacyVersionPolicyFlag = "workflow-version-policy" +) + type packageExportFlags struct { instance instanceFlags + agentIDs []string workflowIDs []string folderIDs []string projectIDs []string includeVariableValues bool includeTags bool includeArchived bool - missingPolicy string + dependencyPolicy string versionPolicy string credentialPolicy string input string @@ -69,18 +81,20 @@ func newPackageExportCommand(opts Options) *cobra.Command { var f packageExportFlags cmd := &cobra.Command{ Use: "export", - Short: "Export workflows, folders, or projects as an n8n package (beta)", - Long: "Export workflows and/or folders, or whole projects, as a gzipped tar\n" + - "archive (.n8np) streamed to a local file. Pass --workflow-id and/or\n" + - "--folder-id for loose workflows and folders, or --project-id for whole\n" + - "projects, but not both groups in the same request; at least one ID is\n" + - "required. Each exported folder includes its nested folders.\n\n" + + Short: "Export agents, workflows, folders, or projects as an n8n package (beta)", + Long: "Export agents, workflows, and/or folders, or whole projects, as a gzipped\n" + + "tar archive (.n8np) streamed to a local file. Pass --agent-id,\n" + + "--workflow-id, and/or --folder-id for loose entities, or --project-id for\n" + + "whole projects, but not both groups in the same request; at least one ID\n" + + "is required. Each exported folder includes its nested folders, and whole\n" + + "projects include their agents when the agents module is enabled.\n\n" + "Beta: breaking changes may still occur without a major version bump.\n" + - "Requires the licensed Packages feature: workflow and folder exports need\n" + - "workflow:export, project exports need project:export, and exports that\n" + - "reference variables with values included also need variable:list.\n" + - "Statically referenced sub-workflows must be included or the export is\n" + - "rejected under the default missing-dependency policy. The archive may\n" + + "Requires the licensed Packages feature: agent exports need agent:export\n" + + "and the agents module, workflow and folder exports need workflow:export,\n" + + "project exports need project:export, and exports that reference\n" + + "variables with values included also need variable:list. Workflow and\n" + + "agent dependencies outside the selection must be included or the export\n" + + "is rejected under the default --dependency-policy fail. The archive may\n" + "bundle variable values and credential expressions, so it is written with\n" + "owner-only file permissions and the destination file is overwritten.\n\n" + "Pass the selection as flags, or the whole request document with --input\n" + @@ -91,27 +105,39 @@ func newPackageExportCommand(opts Options) *cobra.Command { "server-side. Follow with 'n8n package import' to restore the archive.", Example: " n8n package export --workflow-id 2tUt1wbLX592XDdX --out workflows.n8np\n" + " n8n package export --workflow-id a --folder-id 9xKp2mNqRzAbCdEf --out mixed.n8np\n" + - " n8n package export --project-id Ox8O54VQrmBrb4qL --out project.n8np --output json\n" + + " n8n package export --project-id Ox8O54VQrmBrb4qL --dependency-policy include-in-package --out project.n8np --output json\n" + + " n8n package export --agent-id uT9LdQx7rK2MvB4f --version-policy prefer-published --out agent.n8np\n" + " n8n package export --input selection.json --out workflows.n8np", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - changed := map[string]bool{ - "include-variable-values": cmd.Flags().Changed("include-variable-values"), - "include-tags": cmd.Flags().Changed("include-tags"), - "include-archived": cmd.Flags().Changed("include-archived"), + changed := map[string]bool{} + for _, name := range []string{ + "include-variable-values", "include-tags", "include-archived", + packageDependencyPolicyFlag, packageLegacyDependencyPolicyFlag, + packageVersionPolicyFlag, packageLegacyVersionPolicyFlag, + } { + changed[name] = cmd.Flags().Changed(name) } return runPackageExport(cmd.Context(), opts, f, changed) }, } + // Deprecation notices go to the flag set output; cobra would otherwise + // print them on stdout, which carries the archive or the JSON summary. + cmd.Flags().SetOutput(opts.Streams.Err) f.instance.register(cmd) + cmd.Flags().StringArrayVar(&f.agentIDs, "agent-id", nil, "agent to include, repeatable up to 300; needs the agents module (cannot combine with --project-id or --input)") cmd.Flags().StringArrayVar(&f.workflowIDs, "workflow-id", nil, "workflow to include, repeatable up to 300 (cannot combine with --project-id or --input)") cmd.Flags().StringArrayVar(&f.folderIDs, "folder-id", nil, "folder to include with nested folders, repeatable up to 300 (cannot combine with --project-id or --input)") - cmd.Flags().StringArrayVar(&f.projectIDs, "project-id", nil, "project to include, repeatable (cannot combine with --workflow-id, --folder-id, or --input)") + cmd.Flags().StringArrayVar(&f.projectIDs, "project-id", nil, "project to include with its workflows and agents, repeatable up to 300 (cannot combine with --agent-id, --workflow-id, --folder-id, or --input)") cmd.Flags().BoolVar(&f.includeVariableValues, "include-variable-values", true, "bundle referenced variable values, else names only (default: true)") cmd.Flags().BoolVar(&f.includeTags, "include-tags", true, "bundle workflow tags, else no tag files or references (default: true)") cmd.Flags().BoolVar(&f.includeArchived, "include-archived", false, "include archived workflows in folder and project exports; listed workflows always export (default: false)") - cmd.Flags().StringVar(&f.missingPolicy, "missing-workflow-dependency-policy", "", "missing static sub-workflow handling: fail, reference-only, or include-in-package (default: server default fail)") - cmd.Flags().StringVar(&f.versionPolicy, "workflow-version-policy", "", "which workflow version travels: published-strict, prefer-published, ignore-unpublished, or latest (default: server default latest)") + cmd.Flags().StringVar(&f.dependencyPolicy, packageDependencyPolicyFlag, "", "workflow and agent dependencies outside the selection: fail, reference-only, or include-in-package (default: server default fail)") + cmd.Flags().StringVar(&f.versionPolicy, packageVersionPolicyFlag, "", "which workflow and agent version travels: published-strict, prefer-published, ignore-unpublished, or latest (default: server default latest)") + cmd.Flags().StringVar(&f.dependencyPolicy, packageLegacyDependencyPolicyFlag, "", "deprecated alias of --dependency-policy, same values (default: server default fail)") + cmd.Flags().StringVar(&f.versionPolicy, packageLegacyVersionPolicyFlag, "", "deprecated alias of --version-policy, same values (default: server default latest)") + _ = cmd.Flags().MarkDeprecated(packageLegacyDependencyPolicyFlag, "use --"+packageDependencyPolicyFlag) + _ = cmd.Flags().MarkDeprecated(packageLegacyVersionPolicyFlag, "use --"+packageVersionPolicyFlag) cmd.Flags().StringVar(&f.credentialPolicy, "credential-export-policy", "", "credential data handling: expression-values-only or no-values; literal values never travel (default: server default expression-values-only)") cmd.Flags().StringVar(&f.input, "input", "", "export selection as JSON: a file path, or - for stdin (cannot combine with selection or policy flags; maximum 1 MiB)") cmd.Flags().StringVar(&f.out, "out", "", "local destination for the .n8np archive: a file path, or - for stdout raw bytes (required)") @@ -137,12 +163,13 @@ func runPackageExport(ctx context.Context, opts Options, f packageExportFlags, c if err != nil { return err } + need := packageExportScopes(request) toStdout := strings.TrimSpace(f.out) == "-" if toStdout { result, err := client.ExportPackage(ctx, request, opts.Streams.Out) if err != nil { - return packageAPIError(err, resolution, "export") + return packageAPIError(err, resolution, "export", need) } if f.output == outputJSON { return writeJSON(opts.Streams.Err, packageExportSummary{Result: result, File: "-"}) @@ -158,7 +185,7 @@ func runPackageExport(ctx context.Context, opts Options, f packageExportFlags, c closeErr := file.Close() if exportErr != nil { _ = os.Remove(f.out) - return packageAPIError(exportErr, resolution, "export") + return packageAPIError(exportErr, resolution, "export", need) } if closeErr != nil { _ = os.Remove(f.out) @@ -177,11 +204,35 @@ type packageExportSummary struct { File string `json:"file"` } +// packageExportScopes names the API key scopes the selection needs: each +// explicitly selected entity type has its own export scope. +func packageExportScopes(request n8n.ExportPackageRequest) scopeNeed { + var scopes []string + if len(request.AgentIDs) > 0 { + scopes = append(scopes, "agent:export") + } + if len(request.WorkflowIDs) > 0 || len(request.FolderIDs) > 0 { + scopes = append(scopes, "workflow:export") + } + if len(request.ProjectIDs) > 0 { + scopes = append(scopes, "project:export") + } + return allOf(scopes...) +} + func packageExportRequest(opts Options, f packageExportFlags, changed map[string]bool) (n8n.ExportPackageRequest, error) { var request n8n.ExportPackageRequest + if changed[packageDependencyPolicyFlag] && changed[packageLegacyDependencyPolicyFlag] { + return request, fmt.Errorf("--%s and its deprecated alias --%s cannot both be set: pass only --%s", + packageDependencyPolicyFlag, packageLegacyDependencyPolicyFlag, packageDependencyPolicyFlag) + } + if changed[packageVersionPolicyFlag] && changed[packageLegacyVersionPolicyFlag] { + return request, fmt.Errorf("--%s and its deprecated alias --%s cannot both be set: pass only --%s", + packageVersionPolicyFlag, packageLegacyVersionPolicyFlag, packageVersionPolicyFlag) + } hasInput := strings.TrimSpace(f.input) != "" - hasFlags := len(f.workflowIDs) > 0 || len(f.folderIDs) > 0 || len(f.projectIDs) > 0 || - strings.TrimSpace(f.missingPolicy) != "" || strings.TrimSpace(f.versionPolicy) != "" || + hasFlags := len(f.agentIDs) > 0 || len(f.workflowIDs) > 0 || len(f.folderIDs) > 0 || len(f.projectIDs) > 0 || + strings.TrimSpace(f.dependencyPolicy) != "" || strings.TrimSpace(f.versionPolicy) != "" || strings.TrimSpace(f.credentialPolicy) != "" || changed["include-variable-values"] || changed["include-tags"] || changed["include-archived"] switch { @@ -191,12 +242,13 @@ func packageExportRequest(opts Options, f packageExportFlags, changed map[string return readPackageExportDocument(opts, f.input) default: request = n8n.ExportPackageRequest{ - WorkflowIDs: f.workflowIDs, - FolderIDs: f.folderIDs, - ProjectIDs: f.projectIDs, - MissingDependencyPolicy: strings.TrimSpace(f.missingPolicy), - WorkflowVersionPolicy: strings.TrimSpace(f.versionPolicy), - CredentialExportPolicy: strings.TrimSpace(f.credentialPolicy), + AgentIDs: f.agentIDs, + WorkflowIDs: f.workflowIDs, + FolderIDs: f.folderIDs, + ProjectIDs: f.projectIDs, + DependencyPolicy: strings.TrimSpace(f.dependencyPolicy), + VersionPolicy: strings.TrimSpace(f.versionPolicy), + CredentialExportPolicy: strings.TrimSpace(f.credentialPolicy), } if changed["include-variable-values"] { request.IncludeVariableValues = n8n.Bool(f.includeVariableValues) @@ -229,6 +281,9 @@ func readPackageExportDocument(opts Options, path string) (n8n.ExportPackageRequ if len(raw) > maxPackageDocument { return request, fmt.Errorf("package export JSON exceeds %d bytes", maxPackageDocument) } + if err := rejectRenamedExportFields(raw); err != nil { + return request, err + } decoder := json.NewDecoder(bytes.NewReader(raw)) decoder.DisallowUnknownFields() if err := decoder.Decode(&request); err != nil { @@ -244,6 +299,22 @@ func readPackageExportDocument(opts Options, path string) (n8n.ExportPackageRequ return request, nil } +// rejectRenamedExportFields names the current field when a document still +// uses a pre-rename one; the instance would reject the old name with a 400. +// A document that is not an object is left to the strict decode to report. +func rejectRenamedExportFields(raw []byte) error { + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil + } + for _, old := range slices.Sorted(maps.Keys(n8n.RenamedExportFields)) { + if _, ok := fields[old]; ok { + return fmt.Errorf("decode package export JSON: field %q was renamed to %q: rename it in the document and retry", old, n8n.RenamedExportFields[old]) + } + } + return nil +} + func writePackageExportText(opts Options, resolution config.Resolution, result *n8n.ExportPackageResult, file string) error { writer := io.Writer(opts.Streams.Out) if file == "-" { @@ -328,13 +399,17 @@ func newPackageImportCommand(opts Options) *cobra.Command { "workflows the package does not contain (archive is recoverable,\n" + "hard-delete also drops executions permanently, so prefer archive),\n" + "missing credentials become empty stubs unless --credential-missing-mode\n" + - "must-preexist, and folders, tags, variables, or tables may be created or\n" + - "overwritten. Interactive runs ask for confirmation and non-interactive\n" + - "runs require --yes; --file - also requires --yes because stdin cannot\n" + - "answer. Needs workflow:import plus, depending on the package and the\n" + - "policies, variable, tag, data-table, folder, and delete scopes, and the\n" + - "Packages, Variables, and Folders features where the contents require\n" + - "them.", + "is must-preexist or create-with-values, --data-table-schema-policy\n" + + "overwrite permanently drops the values in removed or retyped columns,\n" + + "and folders, tags, variables, or tables may be created or overwritten.\n" + + "Interactive runs ask for confirmation and non-interactive runs require\n" + + "--yes; --file - also requires --yes because stdin cannot answer.\n" + + "Credentials created from incomplete package data are reported on\n" + + "stderr and keep their workflows unpublished until completed. Needs\n" + + "workflow:import plus, depending on the package and the policies,\n" + + "credential, variable, tag, data-table, folder, and delete scopes, and\n" + + "the Packages, Variables, and Folders features where the contents\n" + + "require them.", Example: " n8n package import --file workflows.n8np --workflow-conflict-policy new-version --yes\n" + " n8n package import --file project.n8np --workflow-conflict-policy fail --project-id Ox8O54VQrmBrb4qL --yes --output json\n" + " n8n package import --file update.n8np --workflow-conflict-policy skip --workflow-publishing-policy publish-all --yes", @@ -348,7 +423,7 @@ func newPackageImportCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.projectID, "project-id", "", "target project ID, from 'n8n project list' (default: the caller's personal project)") cmd.Flags().StringVar(&f.folderID, "folder-id", "", "folder within the target project, from 'n8n folder list PROJECT_ID' (default: the project root)") cmd.Flags().StringVar(&f.credentialMatching, "credential-matching-mode", "", "how package credential references match: id-only, name-and-type, or type-only (default: server default id-only)") - cmd.Flags().StringVar(&f.credentialMissing, "credential-missing-mode", "", "unresolvable credential handling: must-preexist rejects, create-stub creates empty placeholders (default: server default create-stub)") + cmd.Flags().StringVar(&f.credentialMissing, "credential-missing-mode", "", "unresolvable credential handling: must-preexist rejects, create-stub creates empty placeholders, create-with-values seeds them from the package's expression values (needs credential:create; unconfirmed data lands in credentials.incomplete and blocks publishing) (default: server default create-stub)") cmd.Flags().StringVar(&f.bindings, "bindings", "", "explicit credential bindings as JSON, e.g. '{\"credentials\":{\"pkg-id\":\"target-id\"}}' (default: server default {})") cmd.Flags().StringVar(&f.workflowConflict, "workflow-conflict-policy", "", "matching workflow handling, required: new-version, fail, or skip") cmd.Flags().StringVar(&f.workflowIDPolicy, "workflow-id-policy", n8n.ImportWorkflowIDSource, "ID for newly created workflows, always sent: source reuses the package ID for promotions, new mints a fresh ID for repeat imports (default: source)") @@ -359,7 +434,7 @@ func newPackageImportCommand(opts Options) *cobra.Command { cmd.Flags().StringVar(&f.deletionPolicy, "overwrite-deletion-policy", "", "how folder overwrite removes missing workflows: archive (recoverable) or hard-delete (also drops executions; prefer archive) (default: server default archive)") cmd.Flags().StringVar(&f.dataTableMatching, "data-table-matching-mode", "", "data-table matching: by-id, the only mode (default: server default by-id)") cmd.Flags().StringVar(&f.dataTableMissing, "data-table-missing-mode", "", "missing data-table handling: create, must-preexist, or do-nothing (default: server default create)") - cmd.Flags().StringVar(&f.dataTableSchema, "data-table-schema-policy", "", "matched table schema strictness: keep-existing or fail (default: server default keep-existing)") + cmd.Flags().StringVar(&f.dataTableSchema, "data-table-schema-policy", "", "matched table schema handling: keep-existing accepts extra target columns, fail rejects any difference, overwrite reshapes the table to the package and permanently drops values in removed or retyped columns for every workflow using it, overwrite-non-destructive applies the same changes but rejects removals and retypes; rows are kept (default: server default keep-existing)") cmd.Flags().StringVar(&f.variableMissing, "variable-missing-mode", "", "missing variable handling: do-nothing, must-preexist, create-stub, or create-with-value (default: server default create-with-value)") cmd.Flags().StringVar(&f.variableConflict, "variable-conflict-policy", "", "differing variable value handling: keep-existing, overwrite (may rewrite globals), or fail (default: server default keep-existing)") cmd.Flags().StringVar(&f.variableParent, "variable-parent-policy", "", "where workflow and folder packages create missing variables: project or global; omit for project packages, which reject it (default: import target project)") @@ -419,7 +494,7 @@ func runPackageImport(ctx context.Context, opts Options, f packageImportFlags) e defer cleanup() result, err := client.ImportPackage(ctx, request, archive, filename) if err != nil { - return packageAPIError(err, resolution, "import") + return packageAPIError(err, resolution, "import", allOf("workflow:import")) } if f.output == outputJSON { return writeJSON(opts.Streams.Out, result) @@ -455,13 +530,23 @@ func packageImportQuestion(f packageImportFlags, resolution config.Resolution) s if strings.TrimSpace(f.publishingPolicy) != "" { question += fmt.Sprintf(" Publishing uses %q.", strings.TrimSpace(f.publishingPolicy)) } + credentials := "Missing credentials become stubs" + switch strings.TrimSpace(f.credentialMissing) { + case n8n.ImportCredentialMissingCreateWithValues: + credentials = "Missing credentials are created from the package's expression values" + case n8n.ImportCredentialMissingMustPreexist: + credentials = "Missing credentials reject the import" + } switch { case strings.TrimSpace(f.folderConflict) == n8n.ImportFolderOverwrite && strings.TrimSpace(f.deletionPolicy) == n8n.ImportDeletionHardDelete: question += " Folder overwrite with hard-delete permanently deletes workflows the package does not contain, with their executions; prefer archive." case strings.TrimSpace(f.folderConflict) == n8n.ImportFolderOverwrite || strings.TrimSpace(f.projectConflict) == n8n.ImportProjectOverwrite: question += " Overwrite removes workflows the package does not contain (archived by default) and reconciles folders, projects, tags, variables, and tables." default: - question += " Missing credentials become stubs, and folders, tags, variables, or tables may be created or overwritten." + question += " " + credentials + ", and folders, tags, variables, or tables may be created or overwritten." + } + if strings.TrimSpace(f.dataTableSchema) == n8n.ImportDataTableSchemaOverwrite { + question += " Data-table schema overwrite reshapes matched tables to the package and permanently deletes the values in removed or retyped columns, for every workflow using those tables." } return question } @@ -503,8 +588,9 @@ func writePackageImportText(opts Options, resolution config.Resolution, result * fmt.Fprintf(tw, "Imported:\t%d workflows (%d created, %d updated, %d skipped)\n", len(result.Workflows), created, updated, skipped) fmt.Fprintf(tw, "Removed:\t%d workflows, %d folders\n", len(result.RemovedWorkflows), len(result.RemovedFolders)) fmt.Fprintf(tw, "Shells:\t%d folders, %d projects\n", len(result.Folders), len(result.Projects)) - fmt.Fprintf(tw, "Credentials:\t%d matched, %d stubbed\n", len(result.Credentials.Matched), len(result.Credentials.Stubbed)) - fmt.Fprintf(tw, "Data tables:\t%d matched, %d created\n", result.DataTables.Matched, result.DataTables.Created) + fmt.Fprintf(tw, "Credentials:\t%d matched, %d stubbed, %d seeded, %d incomplete\n", + len(result.Credentials.Matched), len(result.Credentials.Stubbed), len(result.Credentials.Seeded), len(result.Credentials.Incomplete)) + fmt.Fprintf(tw, "Data tables:\t%d matched, %d created, %d updated\n", result.DataTables.Matched, result.DataTables.Created, result.DataTables.Updated) fmt.Fprintf(tw, "Variables:\t%d matched, %d created, %d stubbed, %d updated, %d missing\n", len(result.Variables.Matched), len(result.Variables.Created), len(result.Variables.Stubbed), len(result.Variables.Updated), len(result.Variables.Missing)) fmt.Fprintf(tw, "Tags:\t%d matched, %d created, %d renamed, %d reconciled, %d skipped\n", @@ -521,6 +607,10 @@ func writePackageImportText(opts Options, resolution config.Resolution, result * if err := tw.Flush(); err != nil { return err } + if len(result.Credentials.Incomplete) > 0 { + fmt.Fprintf(opts.Streams.Err, "%d credential(s) created from package data that may be incomplete (%s): workflows using them stay unpublished until you complete each with 'n8n credential update '; see credentials.incomplete in --output json.\n", + len(result.Credentials.Incomplete), strings.Join(importedCredentialIDs(result), ", ")) + } if len(result.Variables.Missing) > 0 { fmt.Fprintf(opts.Streams.Err, "%d variable(s) still unresolved: workflows referencing them may fail until the variables exist.\n", len(result.Variables.Missing)) } @@ -539,7 +629,23 @@ func writePackageImportText(opts Options, resolution config.Resolution, result * return nil } -func packageAPIError(err error, resolution config.Resolution, action string) error { +// importedCredentialIDs maps the incomplete source credential IDs to their IDs +// on this instance, keeping the source ID when no binding names one. +func importedCredentialIDs(result *n8n.ImportPackageResult) []string { + ids := make([]string, 0, len(result.Credentials.Incomplete)) + for _, source := range result.Credentials.Incomplete { + if target := result.Bindings.Credentials[source]; target != "" { + ids = append(ids, target) + continue + } + ids = append(ids, source) + } + return ids +} + +// packageAPIError restates the fix for a failed export or import. need is the +// scope requirement reported on a 403. +func packageAPIError(err error, resolution config.Resolution, action string, need scopeNeed) error { if blocked, ok := n8n.AsImportBlocked(err); ok && action == "import" { if blocked.StatusCode == http.StatusConflict { return fmt.Errorf("%s rejected the package import (409): %d conflict issue(s); nothing matched with fail stays unchanged, so adjust a conflict policy such as --workflow-conflict-policy, --project-conflict-policy, --folder-conflict-policy, --tag-conflict-policy, or --variable-conflict-policy and retry: %w", resolution.URL, len(blocked.Issues), err) @@ -549,16 +655,16 @@ func packageAPIError(err error, resolution config.Resolution, action string) err switch { case n8n.IsStatus(err, http.StatusBadRequest): if action == "export" { - return fmt.Errorf("%s rejected the package export (400): check the selected IDs (unknown, mixed project and loose groups, or missing sub-workflows under fail) and the version policy: %w", resolution.URL, err) + return fmt.Errorf("%s rejected the package export (400): check the selected IDs (unknown, mixed project and loose groups, agents without the agents module, or missing dependencies under --dependency-policy fail) and --version-policy: %w", resolution.URL, err) } return fmt.Errorf("%s rejected the package import (400): the archive is malformed, the manifest is missing, or a routing or policy field is invalid (bindings JSON, --variable-parent-policy on a project package): %w", resolution.URL, err) case n8n.IsForbidden(err): if action == "export" { - return forbiddenScopeError(err, resolution, "package export", allOf("workflow:export", "project:export"), - "project:export applies to project packages, variable:list is needed when values are included, and the instance needs the licensed Packages feature.", packageResource) + return forbiddenScopeError(err, resolution, "package export", need, + "variable:list is also needed when exported entities reference variables and values are included, agent exports need the agents module, and the instance needs the licensed Packages feature.", packageResource) } - return forbiddenScopeError(err, resolution, "package import", allOf("workflow:import"), - "the import also needs the variable, tag, data-table, folder and delete scopes the package and policies require, and the instance needs the licensed Packages feature.", packageResource) + return forbiddenScopeError(err, resolution, "package import", need, + "the import also needs the credential (create-with-values), variable, tag, data-table (dataTable:update for schema overwrite), folder and delete scopes the package and policies require, and the instance needs the licensed Packages feature.", packageResource) case n8n.IsNotFound(err): return fmt.Errorf("%s does not serve n8n packages (404): it needs the licensed Packages feature; run %s to see what this instance offers: %w", resolution.URL, discoverHint(packageResource), err) diff --git a/internal/cli/n8n_package_test.go b/internal/cli/n8n_package_test.go index b5ea999..5fc7527 100644 --- a/internal/cli/n8n_package_test.go +++ b/internal/cli/n8n_package_test.go @@ -133,8 +133,8 @@ func TestPackageExportJSONAndPolicies(t *testing.T) { got := f.run("package", "export", "--project-id", "p1", - "--missing-workflow-dependency-policy", "include-in-package", - "--workflow-version-policy", "latest", + "--dependency-policy", "include-in-package", + "--version-policy", "latest", "--credential-export-policy", "no-values", "--include-archived", "--out", out, "--output", "json") @@ -145,8 +145,8 @@ func TestPackageExportJSONAndPolicies(t *testing.T) { if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { t.Fatalf("request body is not an export: %v", err) } - if len(sent.ProjectIDs) != 1 || sent.MissingDependencyPolicy != "include-in-package" || - sent.WorkflowVersionPolicy != "latest" || sent.CredentialExportPolicy != "no-values" { + if len(sent.ProjectIDs) != 1 || sent.DependencyPolicy != "include-in-package" || + sent.VersionPolicy != "latest" || sent.CredentialExportPolicy != "no-values" { t.Errorf("request = %+v, want the project selection and policies", sent) } if sent.IncludeArchived == nil || !*sent.IncludeArchived { @@ -187,7 +187,11 @@ func TestPackageExportRejectsBadSelectionBeforeTransport(t *testing.T) { cases := [][]string{ {"package", "export", "--out", out}, {"package", "export", "--workflow-id", "a", "--project-id", "p", "--out", out}, + {"package", "export", "--workflow-id", "a", "--dependency-policy", "sometimes", "--out", out}, {"package", "export", "--workflow-id", "a", "--missing-workflow-dependency-policy", "sometimes", "--out", out}, + {"package", "export", "--workflow-id", "a", "--dependency-policy", "fail", "--missing-workflow-dependency-policy", "fail", "--out", out}, + {"package", "export", "--workflow-id", "a", "--version-policy", "latest", "--workflow-version-policy", "latest", "--out", out}, + {"package", "export", "--agent-id", "ag", "--project-id", "p", "--out", out}, {"package", "export", "--workflow-id", "a", "--out", out, "--output", "yaml"}, {"package", "export", "--workflow-id", "a", "--out", out, "--input", input}, {"package", "export", "--workflow-id", "a"}, @@ -207,13 +211,14 @@ func TestPackageExportInputDocument(t *testing.T) { f := packageFixture(t, cliPackageArchive) out := filepath.Join(t.TempDir(), "from-file.n8np") - input := writePackageInput(t, "selection.json", `{"folderIds":["f1"],"workflowVersionPolicy":"latest"}`) + input := writePackageInput(t, "selection.json", `{"agentIds":["ag1"],"folderIds":["f1"],"dependencyPolicy":"reference-only","versionPolicy":"latest"}`) got := f.run("package", "export", "--input", input, "--out", out) if got.code != ExitSuccess { t.Fatalf("input exit = %d, stderr: %s", got.code, got.stderr) } var sent n8n.ExportPackageRequest - if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil || len(sent.FolderIDs) != 1 { + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil || len(sent.FolderIDs) != 1 || len(sent.AgentIDs) != 1 || + sent.DependencyPolicy != "reference-only" || sent.VersionPolicy != "latest" { t.Errorf("request = %q (error %v), want the file document", f.lastBody(), err) } @@ -231,6 +236,103 @@ func TestPackageExportInputDocument(t *testing.T) { } } +func TestPackageExportInputRejectsRenamedFields(t *testing.T) { + f := packageFixture(t, cliPackageArchive) + before := f.requestCount() + + for old, current := range map[string]string{ + "missingWorkflowDependencyPolicy": "dependencyPolicy", + "workflowVersionPolicy": "versionPolicy", + } { + input := writePackageInput(t, "old.json", `{"workflowIds":["a"],"`+old+`":"latest"}`) + got := f.run("package", "export", "--input", input, "--out", filepath.Join(t.TempDir(), "old.n8np")) + if got.code != ExitError || !strings.Contains(got.stderr, old) || !strings.Contains(got.stderr, current) { + t.Errorf("%s: result = %+v, want an error naming %s", old, got, current) + } + } + if f.requestCount() != before { + t.Errorf("requests = %d, want %d before transport", f.requestCount(), before) + } +} + +func TestPackageExportDeprecatedPolicyFlags(t *testing.T) { + f := packageFixture(t, cliPackageArchive) + out := filepath.Join(t.TempDir(), "legacy.n8np") + + got := f.run("package", "export", "--workflow-id", "a", + "--missing-workflow-dependency-policy", "reference-only", + "--workflow-version-policy", "published-strict", + "--out", out, "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var sent map[string]any + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil { + t.Fatalf("request body is not JSON: %v", err) + } + if sent["dependencyPolicy"] != "reference-only" || sent["versionPolicy"] != "published-strict" { + t.Errorf("request = %v, want the aliases sent under the current names", sent) + } + for _, old := range []string{"missingWorkflowDependencyPolicy", "workflowVersionPolicy"} { + if _, present := sent[old]; present { + t.Errorf("request = %v, want no %s", sent, old) + } + } + for _, want := range []string{ + "Flag --missing-workflow-dependency-policy has been deprecated, use --dependency-policy", + "Flag --workflow-version-policy has been deprecated, use --version-policy", + } { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr = %q, want %q", got.stderr, want) + } + } + var summary map[string]any + if err := json.Unmarshal([]byte(got.stdout), &summary); err != nil { + t.Errorf("stdout = %q, want only the JSON summary (error: %v)", got.stdout, err) + } + + help := run(t, "package", "export", "--help") + if strings.Contains(help.stdout, "missing-workflow-dependency-policy") || strings.Contains(help.stdout, "workflow-version-policy") { + t.Errorf("help lists deprecated flags:\n%s", help.stdout) + } +} + +func TestPackageExportStdoutStaysRawWithDeprecatedFlag(t *testing.T) { + f := packageFixture(t, cliPackageArchive) + + got := f.run("package", "export", "--workflow-id", "a", "--workflow-version-policy", "latest", "--out", "-") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + if got.stdout != cliPackageArchive { + t.Errorf("stdout = %q, want only the raw archive bytes", got.stdout) + } +} + +func TestPackageExportAgentsNeedAgentScope(t *testing.T) { + f := packageFixture(t, cliPackageArchive) + out := filepath.Join(t.TempDir(), "agents.n8np") + + got := f.run("package", "export", "--agent-id", "ag1", "--agent-id", "ag2", "--out", out) + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + var sent n8n.ExportPackageRequest + if err := json.Unmarshal([]byte(f.lastBody()), &sent); err != nil || len(sent.AgentIDs) != 2 { + t.Errorf("request = %q (error %v), want two agent IDs", f.lastBody(), err) + } + + f.status = http.StatusForbidden + got = f.run("package", "export", "--agent-id", "ag1", "--out", out) + if got.code != ExitError || !strings.Contains(got.stderr, "agent:export") || strings.Contains(got.stderr, "project:export") { + t.Errorf("403 result = %+v, want agent:export only", got) + } + got = f.run("package", "export", "--project-id", "p1", "--out", out) + if got.code != ExitError || !strings.Contains(got.stderr, "project:export") || strings.Contains(got.stderr, "workflow:export") { + t.Errorf("403 result = %+v, want project:export only", got) + } +} + func TestPackageImportConfirmationPolicyAndBody(t *testing.T) { f := packageFixture(t, cliPackageImportResult) archive := writePackageArchive(t, cliPackageArchive) @@ -296,6 +398,82 @@ func TestPackageImportTextWarnsAboutDroppedItems(t *testing.T) { } } +func TestPackageImportReportsIncompleteCredentials(t *testing.T) { + body := `{ + "package":{"sourceN8nVersion":"2.0.0","sourceId":"pkg-2","exportedAt":"2026-10-01T00:00:00.000Z"}, + "workflows":[],"removedWorkflows":[],"removedFolders":[],"folders":[],"projects":[], + "bindings":{"workflows":{},"credentials":{"c-partial":"t-partial"}}, + "credentials":{"matched":["c-ok"],"stubbed":[],"seeded":["c-seeded"],"incomplete":["c-partial"]}, + "dataTables":{"matched":1,"created":0,"updated":2}, + "variables":{"matched":[],"missing":[],"created":[],"stubbed":[],"updated":[]}, + "tags":{"matched":[],"created":[],"renamed":[],"reconciled":[],"skipped":[]}, + "futureField":{"kept":true} +}` + f := packageFixture(t, body) + archive := writePackageArchive(t, cliPackageArchive) + + got := f.run("package", "import", "--file", archive, "--workflow-conflict-policy", "skip", + "--credential-missing-mode", "create-with-values", "--data-table-schema-policy", "overwrite-non-destructive", "--yes") + if got.code != ExitSuccess { + t.Fatalf("exit = %d, stderr: %s", got.code, got.stderr) + } + fields, _, _ := parseCLIImportMultipart(t, f) + if fields["credentialMissingMode"] != "create-with-values" || fields["dataTableSchemaConflictPolicy"] != "overwrite-non-destructive" { + t.Errorf("fields = %v, want the new modes sent", fields) + } + for _, want := range []string{"1 matched, 0 stubbed, 1 seeded, 1 incomplete", "1 matched, 0 created, 2 updated"} { + if !strings.Contains(got.stdout, want) { + t.Errorf("stdout missing %q:\n%s", want, got.stdout) + } + } + for _, want := range []string{"1 credential(s)", "t-partial", "n8n credential update"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, got.stderr) + } + } + + got = f.run("package", "import", "--file", archive, "--workflow-conflict-policy", "skip", "--yes", "--output", "json") + if got.code != ExitSuccess { + t.Fatalf("json exit = %d, stderr: %s", got.code, got.stderr) + } + var decoded struct { + Credentials struct { + Seeded []string `json:"seeded"` + Incomplete []string `json:"incomplete"` + } `json:"credentials"` + DataTables struct { + Updated int `json:"updated"` + } `json:"dataTables"` + FutureField map[string]bool `json:"futureField"` + } + if err := json.Unmarshal([]byte(got.stdout), &decoded); err != nil { + t.Fatalf("stdout is not JSON: %v\n%s", err, got.stdout) + } + if len(decoded.Credentials.Seeded) != 1 || len(decoded.Credentials.Incomplete) != 1 || decoded.DataTables.Updated != 2 || !decoded.FutureField["kept"] { + t.Errorf("json = %s, want seeded, incomplete, updated, and the unknown field round-tripped", got.stdout) + } +} + +func TestPackageImportSchemaOverwriteWarns(t *testing.T) { + f := packageFixture(t, cliPackageImportResult) + archive := writePackageArchive(t, cliPackageArchive) + before := f.requestCount() + f.stdin = "no\n" + + got := f.run("package", "import", "--file", archive, + "--workflow-conflict-policy", "new-version", + "--data-table-schema-policy", "overwrite", + "--credential-missing-mode", "create-with-values") + if got.code != ExitError || f.requestCount() != before { + t.Fatalf("declined result = %+v, requests = %d want %d", got, f.requestCount(), before) + } + for _, want := range []string{"permanently deletes the values", "every workflow", "created from the package's expression values"} { + if !strings.Contains(got.stderr, want) { + t.Errorf("prompt = %q, want %q", got.stderr, want) + } + } +} + func TestPackageImportStdinRequiresYes(t *testing.T) { f := packageFixture(t, cliPackageImportResult) f.stdin = cliPackageArchive diff --git a/internal/n8n/n8n_package.go b/internal/n8n/n8n_package.go index 0268374..ecd4c5d 100644 --- a/internal/n8n/n8n_package.go +++ b/internal/n8n/n8n_package.go @@ -30,27 +30,28 @@ const ( // ExportCountsHeader carries the JSON-serialized per-entity counts of what // actually ended up in an exported package, e.g. -// {"workflows":2,"folders":1,"credentials":0,"dataTables":0,"variables":0}. +// {"agents":1,"workflows":2,"folders":1,"credentials":0,"dataTables":0,"variables":0,"tags":0}. const ExportCountsHeader = "X-N8n-Export-Counts" // DefaultImportPackageFilename is the multipart filename sent when the caller // supplies no better name for the archive. const DefaultImportPackageFilename = "package.n8np" -// Missing-workflow-dependency policies for an export. +// Dependency policies for an export: how workflow and agent dependencies +// outside the selection are handled. const ( - ExportMissingFail = "fail" - ExportMissingReferenceOnly = "reference-only" - ExportMissingIncludeInPackage = "include-in-package" + ExportDependencyFail = "fail" + ExportDependencyReferenceOnly = "reference-only" + ExportDependencyIncludeInPackage = "include-in-package" ) -var exportMissingPolicies = []string{ - ExportMissingFail, - ExportMissingReferenceOnly, - ExportMissingIncludeInPackage, +var exportDependencyPolicies = []string{ + ExportDependencyFail, + ExportDependencyReferenceOnly, + ExportDependencyIncludeInPackage, } -// Workflow-version policies for an export. +// Version policies for an export: which workflow and agent version travels. const ( ExportVersionPublishedStrict = "published-strict" ExportVersionPreferPublished = "prefer-published" @@ -77,70 +78,72 @@ var exportCredentialPolicies = []string{ ExportCredentialNoValues, } -// maxExportIDs is the per-list limit the schema declares for workflow and -// folder selections. +// maxExportIDs is the per-list limit the schema declares for agent, workflow, +// folder, and project selections. const maxExportIDs = 300 -// ExportPackageRequest selects what to export. Provide workflow and/or folder -// IDs to export loose workflows and folders, or project IDs to export whole +// ExportPackageRequest selects what to export. Provide agent, workflow, and/or +// folder IDs to export loose entities, or project IDs to export whole // projects, but not both groups in the same request. At least one ID must be // supplied. Pointer booleans distinguish an omitted value (the server default // applies) from an explicit false; use [Bool] when setting them directly. type ExportPackageRequest struct { - WorkflowIDs []string `json:"workflowIds,omitempty"` - FolderIDs []string `json:"folderIds,omitempty"` - ProjectIDs []string `json:"projectIds,omitempty"` - IncludeVariableValues *bool `json:"includeVariableValues,omitempty"` - IncludeTags *bool `json:"includeTags,omitempty"` - MissingDependencyPolicy string `json:"missingWorkflowDependencyPolicy,omitempty"` - WorkflowVersionPolicy string `json:"workflowVersionPolicy,omitempty"` - CredentialExportPolicy string `json:"credentialExportPolicy,omitempty"` - IncludeArchived *bool `json:"includeArchivedWorkflows,omitempty"` + AgentIDs []string `json:"agentIds,omitempty"` + WorkflowIDs []string `json:"workflowIds,omitempty"` + FolderIDs []string `json:"folderIds,omitempty"` + ProjectIDs []string `json:"projectIds,omitempty"` + IncludeVariableValues *bool `json:"includeVariableValues,omitempty"` + IncludeTags *bool `json:"includeTags,omitempty"` + DependencyPolicy string `json:"dependencyPolicy,omitempty"` + VersionPolicy string `json:"versionPolicy,omitempty"` + CredentialExportPolicy string `json:"credentialExportPolicy,omitempty"` + IncludeArchived *bool `json:"includeArchivedWorkflows,omitempty"` +} + +// RenamedExportFields maps export fields older instances accepted to the +// names the schema uses now. The body rejects unknown properties, so a +// document still carrying an old name would fail with a 400. +var RenamedExportFields = map[string]string{ + "missingWorkflowDependencyPolicy": "dependencyPolicy", + "workflowVersionPolicy": "versionPolicy", } // Validate rejects an export document the API would reject before transport. func (r ExportPackageRequest) Validate() error { - if len(r.WorkflowIDs) == 0 && len(r.FolderIDs) == 0 && len(r.ProjectIDs) == 0 { - return fmt.Errorf("at least one workflow, folder, or project ID is required") + loose := len(r.AgentIDs) > 0 || len(r.WorkflowIDs) > 0 || len(r.FolderIDs) > 0 + if !loose && len(r.ProjectIDs) == 0 { + return fmt.Errorf("at least one agent, workflow, folder, or project ID is required") } - if len(r.ProjectIDs) > 0 && (len(r.WorkflowIDs) > 0 || len(r.FolderIDs) > 0) { - return fmt.Errorf("projectIds cannot be combined with workflowIds or folderIds: export loose workflows and folders, or whole projects, not both") + if loose && len(r.ProjectIDs) > 0 { + return fmt.Errorf("projectIds cannot be combined with agentIds, workflowIds, or folderIds: export loose agents, workflows, and folders, or whole projects, not both") } - for i, id := range r.WorkflowIDs { - if strings.TrimSpace(id) == "" { - return fmt.Errorf("workflowIds[%d] is required and must not be blank", i) - } - if id != strings.TrimSpace(id) { - return fmt.Errorf("workflowIds[%d] must not start or end with whitespace", i) - } - } - for i, id := range r.FolderIDs { - if strings.TrimSpace(id) == "" { - return fmt.Errorf("folderIds[%d] is required and must not be blank", i) - } - if id != strings.TrimSpace(id) { - return fmt.Errorf("folderIds[%d] must not start or end with whitespace", i) - } - } - for i, id := range r.ProjectIDs { - if strings.TrimSpace(id) == "" { - return fmt.Errorf("projectIds[%d] is required and must not be blank", i) + lists := []struct { + name string + ids []string + }{ + {"agentIds", r.AgentIDs}, + {"workflowIds", r.WorkflowIDs}, + {"folderIds", r.FolderIDs}, + {"projectIds", r.ProjectIDs}, + } + for _, list := range lists { + for i, id := range list.ids { + if strings.TrimSpace(id) == "" { + return fmt.Errorf("%s[%d] is required and must not be blank", list.name, i) + } + if id != strings.TrimSpace(id) { + return fmt.Errorf("%s[%d] must not start or end with whitespace", list.name, i) + } } - if id != strings.TrimSpace(id) { - return fmt.Errorf("projectIds[%d] must not start or end with whitespace", i) + if len(list.ids) > maxExportIDs { + return fmt.Errorf("%s holds %d IDs, want at most %d", list.name, len(list.ids), maxExportIDs) } } - if len(r.WorkflowIDs) > maxExportIDs { - return fmt.Errorf("workflowIds holds %d IDs, want at most %d", len(r.WorkflowIDs), maxExportIDs) - } - if len(r.FolderIDs) > maxExportIDs { - return fmt.Errorf("folderIds holds %d IDs, want at most %d", len(r.FolderIDs), maxExportIDs) - } - if r.MissingDependencyPolicy != "" && !slices.Contains(exportMissingPolicies, r.MissingDependencyPolicy) { - return fmt.Errorf("unknown missing-workflow-dependency policy %q: use %s", r.MissingDependencyPolicy, strings.Join(exportMissingPolicies, ", ")) + if r.DependencyPolicy != "" && !slices.Contains(exportDependencyPolicies, r.DependencyPolicy) { + return fmt.Errorf("unknown dependency policy %q: use %s", r.DependencyPolicy, strings.Join(exportDependencyPolicies, ", ")) } - if r.WorkflowVersionPolicy != "" && !slices.Contains(exportVersionPolicies, r.WorkflowVersionPolicy) { - return fmt.Errorf("unknown workflow-version policy %q: use %s", r.WorkflowVersionPolicy, strings.Join(exportVersionPolicies, ", ")) + if r.VersionPolicy != "" && !slices.Contains(exportVersionPolicies, r.VersionPolicy) { + return fmt.Errorf("unknown version policy %q: use %s", r.VersionPolicy, strings.Join(exportVersionPolicies, ", ")) } if r.CredentialExportPolicy != "" && !slices.Contains(exportCredentialPolicies, r.CredentialExportPolicy) { return fmt.Errorf("unknown credential-export policy %q: use %s", r.CredentialExportPolicy, strings.Join(exportCredentialPolicies, ", ")) @@ -151,7 +154,8 @@ func (r ExportPackageRequest) Validate() error { // ExportPackageResult describes the archive streamed to the caller's writer. type ExportPackageResult struct { // Counts holds the per-entity counts from the X-N8n-Export-Counts response - // header, e.g. workflows, folders, credentials, dataTables, variables. + // header, e.g. agents, workflows, folders, credentials, dataTables, + // variables, tags. Counts map[string]int `json:"counts"` // Filename is the attachment name from Content-Disposition, when sent. Filename string `json:"filename,omitempty"` @@ -283,15 +287,16 @@ func exportFilename(header string) string { // Import conflict and mode values. Every optional mode takes its default when // omitted; the CLI sends a field only when its flag is set, except -// WorkflowIDPolicy, which is always sent because the prose default (new) and -// the schema default (source) conflict. +// WorkflowIDPolicy, which is always sent so the ID behavior is stated rather +// than inherited from a server default (source). const ( ImportCredentialMatchIDOnly = "id-only" ImportCredentialMatchNameAndType = "name-and-type" ImportCredentialMatchTypeOnly = "type-only" - ImportCredentialMissingMustPreexist = "must-preexist" - ImportCredentialMissingCreateStub = "create-stub" + ImportCredentialMissingMustPreexist = "must-preexist" + ImportCredentialMissingCreateStub = "create-stub" + ImportCredentialMissingCreateWithValues = "create-with-values" ImportWorkflowConflictNewVersion = "new-version" ImportWorkflowConflictFail = "fail" @@ -325,8 +330,10 @@ const ( ImportDataTableMissingMustPreexist = "must-preexist" ImportDataTableMissingDoNothing = "do-nothing" - ImportDataTableSchemaKeepExisting = "keep-existing" - ImportDataTableSchemaFail = "fail" + ImportDataTableSchemaKeepExisting = "keep-existing" + ImportDataTableSchemaFail = "fail" + ImportDataTableSchemaOverwrite = "overwrite" + ImportDataTableSchemaOverwriteNonDestructive = "overwrite-non-destructive" ImportVariableMissingDoNothing = "do-nothing" ImportVariableMissingMustPreexist = "must-preexist" @@ -350,7 +357,7 @@ const ( var ( importCredentialMatchModes = []string{ImportCredentialMatchIDOnly, ImportCredentialMatchNameAndType, ImportCredentialMatchTypeOnly} - importCredentialMissingModes = []string{ImportCredentialMissingMustPreexist, ImportCredentialMissingCreateStub} + importCredentialMissingModes = []string{ImportCredentialMissingMustPreexist, ImportCredentialMissingCreateStub, ImportCredentialMissingCreateWithValues} importWorkflowConflicts = []string{ImportWorkflowConflictNewVersion, ImportWorkflowConflictFail, ImportWorkflowConflictSkip} importWorkflowIDPolicies = []string{ImportWorkflowIDNew, ImportWorkflowIDSource} importMissingNodeModes = []string{ImportMissingNodeFail, ImportMissingNodeImportAnyway} @@ -360,7 +367,7 @@ var ( importDeletionPolicies = []string{ImportDeletionArchive, ImportDeletionHardDelete} importDataTableMatchModes = []string{ImportDataTableMatchByID} importDataTableMissingModes = []string{ImportDataTableMissingCreate, ImportDataTableMissingMustPreexist, ImportDataTableMissingDoNothing} - importDataTableSchemaModes = []string{ImportDataTableSchemaKeepExisting, ImportDataTableSchemaFail} + importDataTableSchemaModes = []string{ImportDataTableSchemaKeepExisting, ImportDataTableSchemaFail, ImportDataTableSchemaOverwrite, ImportDataTableSchemaOverwriteNonDestructive} importVariableMissingModes = []string{ImportVariableMissingDoNothing, ImportVariableMissingMustPreexist, ImportVariableMissingCreateStub, ImportVariableMissingCreateWithVal} importVariableConflictModes = []string{ImportVariableConflictKeep, ImportVariableConflictOverwrite, ImportVariableConflictFail} importVariableParentModes = []string{ImportVariableParentProject, ImportVariableParentGlobal} @@ -370,9 +377,9 @@ var ( // ImportPackageRequest is the routing and conflict policy for one package // import. Empty optional fields are omitted so the server default applies, -// except WorkflowIDPolicy, which is always sent because the prose default -// (new) and the schema default (source) conflict. Bindings, when set, must be -// a JSON object; only credentials bindings are supported today. +// except WorkflowIDPolicy, which is always sent so the ID behavior is explicit +// (the server default is source). Bindings, when set, must be a JSON object; +// only credentials bindings are supported today. type ImportPackageRequest struct { ProjectID string `json:"-"` FolderID string `json:"-"` @@ -483,6 +490,10 @@ func (r ImportPackageRequest) fields() map[string]string { // ImportPackageResult is the import outcome: what was written, removed, and // how every referenced entity resolved. Names only travel for variables and // tags; values never travel in the response. +// +// Raw keeps the response verbatim so fields this type does not name yet, +// nested ones included, survive --output json. It is a read model: MarshalJSON +// re-emits Raw when present, so edits to the typed fields are not reflected. type ImportPackageResult struct { Package ImportedPackage `json:"package"` Workflows []ImportedWorkflow `json:"workflows"` @@ -495,6 +506,28 @@ type ImportPackageResult struct { DataTables ImportDataTables `json:"dataTables"` Variables ImportVariables `json:"variables"` Tags ImportTags `json:"tags"` + Raw json.RawMessage `json:"-"` +} + +// UnmarshalJSON decodes the named fields and keeps the verbatim document. +func (r *ImportPackageResult) UnmarshalJSON(data []byte) error { + type plain ImportPackageResult + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + *r = ImportPackageResult(decoded) + r.Raw = append(json.RawMessage(nil), data...) + return nil +} + +// MarshalJSON re-emits the verbatim document when present. +func (r ImportPackageResult) MarshalJSON() ([]byte, error) { + if len(r.Raw) > 0 { + return r.Raw, nil + } + type plain ImportPackageResult + return json.Marshal(plain(r)) } // ImportedPackage identifies the package the result came from. @@ -570,17 +603,24 @@ type ImportBindings struct { Credentials map[string]string `json:"credentials"` } -// ImportCredentials groups source credential IDs by whether they matched or -// were created as stubs. +// ImportCredentials groups source credential IDs by outcome: matched an +// existing credential, created as an empty stub, created with all source data +// (seeded), or created from bundled values the package does not confirm are +// complete. Incomplete credentials need input and block publishing of the +// workflows that use them (incomplete-credential). Target IDs are in +// [ImportBindings.Credentials]. type ImportCredentials struct { - Matched []string `json:"matched"` - Stubbed []string `json:"stubbed"` + Matched []string `json:"matched"` + Stubbed []string `json:"stubbed"` + Seeded []string `json:"seeded"` + Incomplete []string `json:"incomplete"` } -// ImportDataTables counts matched and created data tables. +// ImportDataTables counts matched, created, and schema-updated data tables. type ImportDataTables struct { Matched int `json:"matched"` Created int `json:"created"` + Updated int `json:"updated"` } // ImportVariables holds the referenced variable names by outcome. @@ -782,7 +822,7 @@ func (c *Client) ImportPackage(ctx context.Context, request ImportPackageRequest if err != nil { return nil, fmt.Errorf("n8n: POST %s: read error response: %w", N8nPackageImportPath, err) } - return nil, newImportBlockedError(resp, raw) + return nil, newImportBlockedError(resp, N8nPackageImportPath, raw) } if resp.StatusCode < 200 || resp.StatusCode > 299 { raw, truncated, err := readLimited(resp.Body, maxErrorBody) @@ -835,14 +875,15 @@ func writeMultipartImport(multipartWriter *multipart.Writer, request ImportPacka return nil } -// newImportBlockedError decodes a 409 or 422 body, preserving every issue. -// A body that does not decode still yields the status and request ID. -func newImportBlockedError(resp *http.Response, raw []byte) *ImportBlockedError { +// newImportBlockedError decodes a 409 or 422 body from the import endpoint at +// path, preserving every issue. A body that does not decode still yields the +// status and request ID. +func newImportBlockedError(resp *http.Response, path string, raw []byte) *ImportBlockedError { blocked := &ImportBlockedError{ StatusCode: resp.StatusCode, Status: resp.Status, Method: http.MethodPost, - Path: N8nPackageImportPath, + Path: path, RequestID: requestID(resp.Header), } var decoded struct { diff --git a/internal/n8n/n8n_package_test.go b/internal/n8n/n8n_package_test.go index e185483..299ca63 100644 --- a/internal/n8n/n8n_package_test.go +++ b/internal/n8n/n8n_package_test.go @@ -116,6 +116,58 @@ func TestExportPackageOptionalBools(t *testing.T) { } } +func TestExportPackageSendsCurrentFieldNames(t *testing.T) { + server := newCommunityPackageServer(t, exportGzipHandler(t, `{"agents":1,"workflows":1}`, "")) + + var out bytes.Buffer + _, err := server.client(t).ExportPackage(context.Background(), ExportPackageRequest{ + AgentIDs: []string{"ag1"}, + WorkflowIDs: []string{"wf1"}, + DependencyPolicy: ExportDependencyIncludeInPackage, + VersionPolicy: ExportVersionPreferPublished, + }, &out) + if err != nil { + t.Fatalf("ExportPackage: %v", err) + } + _, raw := server.last(t) + var sent map[string]any + if err := json.Unmarshal([]byte(raw), &sent); err != nil { + t.Fatalf("request body is not JSON: %v\n%s", err, raw) + } + want := map[string]any{ + "agentIds": []any{"ag1"}, + "workflowIds": []any{"wf1"}, + "dependencyPolicy": "include-in-package", + "versionPolicy": "prefer-published", + } + if diff := cmp.Diff(want, sent); diff != "" { + t.Errorf("export body mismatch (-want +got):\n%s", diff) + } +} + +func TestExportPackageAcceptsEveryPolicyValue(t *testing.T) { + server := newCommunityPackageServer(t, exportGzipHandler(t, "", "")) + client := server.client(t) + var out bytes.Buffer + for _, policy := range exportDependencyPolicies { + if _, err := client.ExportPackage(context.Background(), ExportPackageRequest{ProjectIDs: []string{"p"}, DependencyPolicy: policy}, &out); err != nil { + t.Errorf("dependency policy %q: %v", policy, err) + } + } + for _, policy := range exportVersionPolicies { + if _, err := client.ExportPackage(context.Background(), ExportPackageRequest{ProjectIDs: []string{"p"}, VersionPolicy: policy}, &out); err != nil { + t.Errorf("version policy %q: %v", policy, err) + } + } + many := make([]string, maxExportIDs) + for i := range many { + many[i] = "p" + } + if _, err := client.ExportPackage(context.Background(), ExportPackageRequest{ProjectIDs: many}, &out); err != nil { + t.Errorf("300 project IDs: %v, want accepted", err) + } +} + func TestExportPackageValidation(t *testing.T) { server := newCommunityPackageServer(t, exportGzipHandler(t, "", "")) client := server.client(t) @@ -127,8 +179,11 @@ func TestExportPackageValidation(t *testing.T) { {WorkflowIDs: []string{" padded "}}, {WorkflowIDs: []string{"a"}, ProjectIDs: []string{"p"}}, {FolderIDs: []string{"f"}, ProjectIDs: []string{"p"}}, - {WorkflowIDs: []string{"a"}, MissingDependencyPolicy: "sometimes"}, - {WorkflowIDs: []string{"a"}, WorkflowVersionPolicy: "sometimes"}, + {AgentIDs: []string{"ag"}, ProjectIDs: []string{"p"}}, + {AgentIDs: []string{" "}}, + {ProjectIDs: []string{"p", ""}}, + {WorkflowIDs: []string{"a"}, DependencyPolicy: "sometimes"}, + {WorkflowIDs: []string{"a"}, VersionPolicy: "sometimes"}, {WorkflowIDs: []string{"a"}, CredentialExportPolicy: "sometimes"}, } for i, request := range cases { @@ -140,8 +195,15 @@ func TestExportPackageValidation(t *testing.T) { for i := range many { many[i] = "w" } - if _, err := client.ExportPackage(context.Background(), ExportPackageRequest{WorkflowIDs: many}, &out); err == nil { - t.Error("301 workflow IDs: want a validation error") + for name, request := range map[string]ExportPackageRequest{ + "agentIds": {AgentIDs: many}, + "workflowIds": {WorkflowIDs: many}, + "folderIds": {FolderIDs: many}, + "projectIds": {ProjectIDs: many}, + } { + if _, err := client.ExportPackage(context.Background(), request, &out); err == nil || !strings.Contains(err.Error(), name) { + t.Errorf("301 %s: error = %v, want a validation error naming the field", name, err) + } } if len(server.requests) != 0 { t.Errorf("requests = %d, want 0 before transport", len(server.requests)) @@ -302,6 +364,94 @@ func TestImportPackageStreamsMultipart(t *testing.T) { } } +func TestImportPackageAcceptsNewModes(t *testing.T) { + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON)) + client := server.client(t) + + for _, tc := range []struct { + credential, schema string + }{ + {ImportCredentialMissingCreateWithValues, ImportDataTableSchemaOverwrite}, + {ImportCredentialMissingCreateStub, ImportDataTableSchemaOverwriteNonDestructive}, + } { + _, err := client.ImportPackage(context.Background(), ImportPackageRequest{ + WorkflowConflictPolicy: ImportWorkflowConflictSkip, + WorkflowIDPolicy: ImportWorkflowIDSource, + CredentialMissingMode: tc.credential, + DataTableSchemaConflict: tc.schema, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if err != nil { + t.Fatalf("ImportPackage(%s, %s): %v", tc.credential, tc.schema, err) + } + req, raw := server.last(t) + fields, _, _ := parseMultipartImport(t, req, []byte(raw)) + if fields["credentialMissingMode"] != tc.credential || fields["dataTableSchemaConflictPolicy"] != tc.schema { + t.Errorf("fields = %v, want credential %q and schema %q", fields, tc.credential, tc.schema) + } + } +} + +func TestImportPackageResultKeepsNewFields(t *testing.T) { + body := `{ + "package":{"sourceN8nVersion":"2.0.0","sourceId":"pkg-2","exportedAt":"2026-10-01T00:00:00.000Z"}, + "workflows":[],"removedWorkflows":[],"removedFolders":[],"folders":[],"projects":[], + "bindings":{"workflows":{},"credentials":{"c-seeded":"t-seeded","c-partial":"t-partial"}}, + "credentials":{"matched":[],"stubbed":[],"seeded":["c-seeded"],"incomplete":["c-partial"],"futureBucket":["x"]}, + "dataTables":{"matched":1,"created":0,"updated":2}, + "variables":{"matched":[],"missing":[],"created":[],"stubbed":[],"updated":[]}, + "tags":{"matched":[],"created":[],"renamed":[],"reconciled":[],"skipped":[]}, + "agents":{"created":["ag-1"]} +}` + server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, body)) + + result, err := server.client(t).ImportPackage(context.Background(), ImportPackageRequest{ + WorkflowConflictPolicy: ImportWorkflowConflictSkip, + WorkflowIDPolicy: ImportWorkflowIDSource, + }, strings.NewReader(packageArchiveBytes), "p.n8np") + if err != nil { + t.Fatalf("ImportPackage: %v", err) + } + wantCredentials := ImportCredentials{Matched: []string{}, Stubbed: []string{}, Seeded: []string{"c-seeded"}, Incomplete: []string{"c-partial"}} + if diff := cmp.Diff(wantCredentials, result.Credentials); diff != "" { + t.Errorf("credentials mismatch (-want +got):\n%s", diff) + } + if diff := cmp.Diff(ImportDataTables{Matched: 1, Updated: 2}, result.DataTables); diff != "" { + t.Errorf("data tables mismatch (-want +got):\n%s", diff) + } + + encoded, err := json.Marshal(result) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + var got, want any + if err := json.Unmarshal(encoded, &got); err != nil { + t.Fatalf("re-decode: %v", err) + } + if err := json.Unmarshal([]byte(body), &want); err != nil { + t.Fatalf("decode fixture: %v", err) + } + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("round trip lost data (-want +got):\n%s", diff) + } + + built := ImportPackageResult{DataTables: ImportDataTables{Updated: 3}} + encoded, err = json.Marshal(built) + if err != nil || !strings.Contains(string(encoded), `"updated":3`) { + t.Errorf("Marshal without raw = %s (error %v), want the typed fields", encoded, err) + } +} + +func TestImportBlockedErrorNamesItsPath(t *testing.T) { + resp := &http.Response{StatusCode: http.StatusConflict, Status: "409 Conflict", Header: http.Header{}} + blocked := newImportBlockedError(resp, "/n8n-packages/import-selection", []byte(`{"message":"overlap","issues":[{"type":"workflow-removal-conflict"}]}`)) + if blocked.Path != "/n8n-packages/import-selection" { + t.Errorf("path = %q, want the selection endpoint", blocked.Path) + } + if !strings.Contains(blocked.Error(), "POST /n8n-packages/import-selection") { + t.Errorf("error = %q, want the path in the message", blocked.Error()) + } +} + func TestImportPackageDefaultsFilename(t *testing.T) { server := newCommunityPackageServer(t, packageJSONHandler(http.StatusOK, packageImportResultJSON))