fix: handle merge conflict

This commit is contained in:
Mutasem Aldmour 2024-11-07 16:32:25 +01:00
commit f121cbdfac
No known key found for this signature in database
GPG key ID: 3DFA8122BB7FD6B8
66 changed files with 3448 additions and 3645 deletions

View file

@ -42,7 +42,7 @@ jobs:
uses: actions/cache/save@v4.0.0
with:
path: ./packages/**/dist
key: ${{ github.sha }}-base:build
key: ${{ github.sha }}-release:build
- name: Dry-run publishing
run: pnpm publish -r --no-git-checks --dry-run
@ -141,7 +141,7 @@ jobs:
uses: actions/cache/restore@v4.0.0
with:
path: ./packages/**/dist
key: ${{ github.sha }}:db-tests
key: ${{ github.sha }}-release:build
- name: Create a frontend release
uses: getsentry/action-release@v1.7.0

View file

@ -795,4 +795,46 @@ describe('NDV', () => {
.find('[data-test-id=run-data-schema-item]')
.should('contain.text', 'onlyOnItem3');
});
it('should keep search expanded after Test step node run', () => {
cy.createFixtureWorkflow('Test_ndv_search.json');
workflowPage.actions.zoomToFit();
workflowPage.actions.executeWorkflow();
workflowPage.actions.openNode('Edit Fields');
ndv.getters.outputPanel().should('be.visible');
ndv.getters.outputPanel().findChildByTestId('ndv-search').click().type('US');
ndv.getters.outputTableRow(1).find('mark').should('have.text', 'US');
ndv.actions.execute();
ndv.getters
.outputPanel()
.findChildByTestId('ndv-search')
.should('be.visible')
.should('have.value', 'US');
});
it('should not show items count when seaching in schema view', () => {
cy.createFixtureWorkflow('Test_ndv_search.json');
workflowPage.actions.zoomToFit();
workflowPage.actions.openNode('Edit Fields');
ndv.getters.outputPanel().should('be.visible');
ndv.actions.execute();
ndv.actions.switchOutputMode('Schema');
ndv.getters.outputPanel().find('[data-test-id=ndv-search]').click().type('US');
ndv.getters.outputPanel().find('[data-test-id=ndv-items-count]').should('not.exist');
});
it('should show additional tooltip when seaching in schema view if no matches', () => {
cy.createFixtureWorkflow('Test_ndv_search.json');
workflowPage.actions.zoomToFit();
workflowPage.actions.openNode('Edit Fields');
ndv.getters.outputPanel().should('be.visible');
ndv.actions.execute();
ndv.actions.switchOutputMode('Schema');
ndv.getters.outputPanel().find('[data-test-id=ndv-search]').click().type('foo');
ndv.getters
.outputPanel()
.contains('To search field contents rather than just names, use Table or JSON view')
.should('exist');
});
});

View file

@ -0,0 +1,135 @@
{
"name": "NDV search bugs (introduced by schema view?)",
"nodes": [
{
"parameters": {},
"id": "55635c7b-92ee-4d2d-a0c0-baff9ab071da",
"name": "When clicking Test workflow",
"type": "n8n-nodes-base.manualTrigger",
"position": [
800,
380
],
"typeVersion": 1
},
{
"parameters": {
"operation": "getAllPeople"
},
"id": "4737af43-e49b-4c92-b76f-32605c047114",
"name": "Customer Datastore (n8n training)",
"type": "n8n-nodes-base.n8nTrainingCustomerDatastore",
"typeVersion": 1,
"position": [
1020,
380
]
},
{
"parameters": {
"assignments": {
"assignments": []
},
"includeOtherFields": true,
"options": {}
},
"id": "8cc9b374-1856-4f3f-9315-08e6e27840d8",
"name": "Edit Fields",
"type": "n8n-nodes-base.set",
"typeVersion": 3.4,
"position": [
1240,
380
]
}
],
"pinData": {
"Customer Datastore (n8n training)": [
{
"json": {
"id": "23423532",
"name": "Jay Gatsby",
"email": "gatsby@west-egg.com",
"notes": "Keeps asking about a green light??",
"country": "US",
"created": "1925-04-10"
}
},
{
"json": {
"id": "23423533",
"name": "José Arcadio Buendía",
"email": "jab@macondo.co",
"notes": "Lots of people named after him. Very confusing",
"country": "CO",
"created": "1967-05-05"
}
},
{
"json": {
"id": "23423534",
"name": "Max Sendak",
"email": "info@in-and-out-of-weeks.org",
"notes": "Keeps rolling his terrible eyes",
"country": "US",
"created": "1963-04-09"
}
},
{
"json": {
"id": "23423535",
"name": "Zaphod Beeblebrox",
"email": "captain@heartofgold.com",
"notes": "Felt like I was talking to more than one person",
"country": null,
"created": "1979-10-12"
}
},
{
"json": {
"id": "23423536",
"name": "Edmund Pevensie",
"email": "edmund@narnia.gov",
"notes": "Passionate sailor",
"country": "UK",
"created": "1950-10-16"
}
}
]
},
"connections": {
"When clicking Test workflow": {
"main": [
[
{
"node": "Customer Datastore (n8n training)",
"type": "main",
"index": 0
}
]
]
},
"Customer Datastore (n8n training)": {
"main": [
[
{
"node": "Edit Fields",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "20178044-fb64-4443-88dd-e941517520d0",
"meta": {
"templateCredsSetupCompleted": true,
"instanceId": "be251a83c052a9862eeac953816fbb1464f89dfbf79d7ac490a8e336a8cc8bfd"
},
"id": "aBVnTRON9Y2cSmse",
"tags": []
}

View file

@ -10,9 +10,8 @@ export type TaskRunnerMode = 'internal_childprocess' | 'internal_launcher' | 'ex
@Config
export class TaskRunnersConfig {
// Defaults to true for now
@Env('N8N_RUNNERS_DISABLED')
disabled: boolean = true;
@Env('N8N_RUNNERS_ENABLED')
enabled: boolean = false;
// Defaults to true for now
@Env('N8N_RUNNERS_MODE')

View file

@ -222,7 +222,7 @@ describe('GlobalConfig', () => {
},
},
taskRunners: {
disabled: true,
enabled: false,
mode: 'internal_childprocess',
path: '/runners',
authToken: '',

View file

@ -221,7 +221,7 @@ export class Start extends BaseCommand {
}
const { taskRunners: taskRunnerConfig } = this.globalConfig;
if (!taskRunnerConfig.disabled) {
if (taskRunnerConfig.enabled) {
const { TaskRunnerModule } = await import('@/runners/task-runner-module');
const taskRunnerModule = Container.get(TaskRunnerModule);
await taskRunnerModule.start();

View file

@ -113,7 +113,7 @@ export class Worker extends BaseCommand {
);
const { taskRunners: taskRunnerConfig } = this.globalConfig;
if (!taskRunnerConfig.disabled) {
if (taskRunnerConfig.enabled) {
const { TaskRunnerModule } = await import('@/runners/task-runner-module');
const taskRunnerModule = Container.get(TaskRunnerModule);
await taskRunnerModule.start();

View file

@ -22,7 +22,7 @@ require('child_process').spawn = spawnMock;
describe('TaskRunnerProcess', () => {
const logger = mockInstance(Logger);
const runnerConfig = mockInstance(TaskRunnersConfig);
runnerConfig.disabled = false;
runnerConfig.enabled = true;
runnerConfig.mode = 'internal_childprocess';
const authService = mock<TaskRunnerAuthService>();
let taskRunnerProcess = new TaskRunnerProcess(logger, runnerConfig, authService);

View file

@ -26,7 +26,7 @@ export class TaskRunnerModule {
constructor(private readonly runnerConfig: TaskRunnersConfig) {}
async start() {
a.ok(!this.runnerConfig.disabled, 'Task runner is disabled');
a.ok(this.runnerConfig.enabled, 'Task runner is disabled');
await this.loadTaskManager();
await this.loadTaskRunnerServer();

View file

@ -1,4 +1,5 @@
import { mock } from 'jest-mock-extended';
import { v4 as uuid } from 'uuid';
import { Project } from '@/databases/entities/project';
import { ProjectRelation } from '@/databases/entities/project-relation';
@ -13,12 +14,15 @@ import { OwnershipService } from '@/services/ownership.service';
import { mockCredential, mockProject } from '@test/mock-objects';
import { mockInstance } from '@test/mocking';
import { CacheService } from '../cache/cache.service';
describe('OwnershipService', () => {
const userRepository = mockInstance(UserRepository);
const sharedWorkflowRepository = mockInstance(SharedWorkflowRepository);
const projectRelationRepository = mockInstance(ProjectRelationRepository);
const cacheService = mockInstance(CacheService);
const ownershipService = new OwnershipService(
mock(),
cacheService,
userRepository,
mock(),
projectRelationRepository,
@ -52,22 +56,22 @@ describe('OwnershipService', () => {
});
});
describe('getProjectOwnerCached()', () => {
describe('getPersonalProjectOwnerCached()', () => {
test('should retrieve a project owner', async () => {
const mockProject = new Project();
const mockOwner = new User();
const projectRelation = Object.assign(new ProjectRelation(), {
role: 'project:personalOwner',
project: mockProject,
user: mockOwner,
});
// ARRANGE
const project = new Project();
const owner = new User();
const projectRelation = new ProjectRelation();
projectRelation.role = 'project:personalOwner';
(projectRelation.project = project), (projectRelation.user = owner);
projectRelationRepository.getPersonalProjectOwners.mockResolvedValueOnce([projectRelation]);
// ACT
const returnedOwner = await ownershipService.getPersonalProjectOwnerCached('some-project-id');
expect(returnedOwner).toBe(mockOwner);
// ASSERT
expect(returnedOwner).toBe(owner);
});
test('should not throw if no project owner found, should return null instead', async () => {
@ -77,6 +81,29 @@ describe('OwnershipService', () => {
expect(owner).toBeNull();
});
test('should not use the repository if the owner was found in the cache', async () => {
// ARRANGE
const project = new Project();
project.id = uuid();
const owner = new User();
owner.id = uuid();
const projectRelation = new ProjectRelation();
projectRelation.role = 'project:personalOwner';
(projectRelation.project = project), (projectRelation.user = owner);
cacheService.getHashValue.mockResolvedValueOnce(owner);
userRepository.create.mockReturnValueOnce(owner);
// ACT
const foundOwner = await ownershipService.getPersonalProjectOwnerCached(project.id);
// ASSERT
expect(cacheService.getHashValue).toHaveBeenCalledTimes(1);
expect(cacheService.getHashValue).toHaveBeenCalledWith('project-owner', project.id);
expect(projectRelationRepository.getPersonalProjectOwners).not.toHaveBeenCalled();
expect(foundOwner).toEqual(owner);
});
});
describe('getProjectOwnerCached()', () => {

View file

@ -45,13 +45,9 @@ export class OwnershipService {
* Personal project ownership is **immutable**.
*/
async getPersonalProjectOwnerCached(projectId: string): Promise<User | null> {
const cachedValue = await this.cacheService.getHashValue<User | null>(
'project-owner',
projectId,
);
const cachedValue = await this.cacheService.getHashValue<User>('project-owner', projectId);
if (cachedValue) this.userRepository.create(cachedValue);
if (cachedValue === null) return null;
if (cachedValue) return this.userRepository.create(cachedValue);
const ownerRel = await this.projectRelationRepository.getPersonalProjectOwners([projectId]);
const owner = ownerRel[0]?.user ?? null;

View file

@ -2,22 +2,29 @@ import type express from 'express';
import { mock } from 'jest-mock-extended';
import type { IdentityProviderInstance, ServiceProviderInstance } from 'samlify';
import { SettingsRepository } from '@/databases/repositories/settings.repository';
import { Logger } from '@/logging/logger.service';
import { UrlService } from '@/services/url.service';
import * as samlHelpers from '@/sso/saml/saml-helpers';
import { SamlService } from '@/sso/saml/saml.service.ee';
import { mockInstance } from '@test/mocking';
import { SAML_PREFERENCES_DB_KEY } from '../constants';
import { InvalidSamlMetadataError } from '../errors/invalid-saml-metadata.error';
describe('SamlService', () => {
const logger = mockInstance(Logger);
const urlService = mockInstance(UrlService);
const samlService = new SamlService(logger, urlService);
const settingsRepository = mockInstance(SettingsRepository);
beforeEach(() => {
jest.restoreAllMocks();
});
describe('getAttributesFromLoginResponse', () => {
test('throws when any attribute is missing', async () => {
//
// ARRANGE
//
jest
.spyOn(samlService, 'getIdentityProviderInstance')
.mockReturnValue(mock<IdentityProviderInstance>());
@ -41,9 +48,7 @@ describe('SamlService', () => {
],
});
//
// ACT & ASSERT
//
await expect(
samlService.getAttributesFromLoginResponse(mock<express.Request>(), 'post'),
).rejects.toThrowError(
@ -51,4 +56,74 @@ describe('SamlService', () => {
);
});
});
describe('init', () => {
test('calls `reset` if an InvalidSamlMetadataError is thrown', async () => {
// ARRANGE
jest
.spyOn(samlService, 'loadFromDbAndApplySamlPreferences')
.mockRejectedValue(new InvalidSamlMetadataError());
jest.spyOn(samlService, 'reset');
// ACT
await samlService.init();
// ASSERT
expect(samlService.reset).toHaveBeenCalledTimes(1);
});
test('calls `reset` if a SyntaxError is thrown', async () => {
// ARRANGE
jest
.spyOn(samlService, 'loadFromDbAndApplySamlPreferences')
.mockRejectedValue(new SyntaxError());
jest.spyOn(samlService, 'reset');
// ACT
await samlService.init();
// ASSERT
expect(samlService.reset).toHaveBeenCalledTimes(1);
});
test('does not call reset and rethrows if another error is thrown', async () => {
// ARRANGE
jest
.spyOn(samlService, 'loadFromDbAndApplySamlPreferences')
.mockRejectedValue(new TypeError());
jest.spyOn(samlService, 'reset');
// ACT & ASSERT
await expect(samlService.init()).rejects.toThrowError(TypeError);
expect(samlService.reset).toHaveBeenCalledTimes(0);
});
test('does not call reset if no error is trown', async () => {
// ARRANGE
jest.spyOn(samlService, 'reset');
// ACT
await samlService.init();
// ASSERT
expect(samlService.reset).toHaveBeenCalledTimes(0);
});
});
describe('reset', () => {
test('disables saml login and deletes the saml `features.saml` key in the db', async () => {
// ARRANGE
jest.spyOn(samlHelpers, 'setSamlLoginEnabled');
jest.spyOn(settingsRepository, 'delete');
// ACT
await samlService.reset();
// ASSERT
expect(samlHelpers.setSamlLoginEnabled).toHaveBeenCalledTimes(1);
expect(samlHelpers.setSamlLoginEnabled).toHaveBeenCalledWith(false);
expect(settingsRepository.delete).toHaveBeenCalledTimes(1);
expect(settingsRepository.delete).toHaveBeenCalledWith({ key: SAML_PREFERENCES_DB_KEY });
});
});
});

View file

@ -0,0 +1,7 @@
import { ApplicationError } from 'n8n-workflow';
export class InvalidSamlMetadataError extends ApplicationError {
constructor() {
super('Invalid SAML metadata', { level: 'warning' });
}
}

View file

@ -16,6 +16,7 @@ import { Logger } from '@/logging/logger.service';
import { UrlService } from '@/services/url.service';
import { SAML_PREFERENCES_DB_KEY } from './constants';
import { InvalidSamlMetadataError } from './errors/invalid-saml-metadata.error';
import {
createUserFromSamlAttributes,
getMappedSamlAttributesFromFlowResult,
@ -81,11 +82,24 @@ export class SamlService {
) {}
async init(): Promise<void> {
// load preferences first but do not apply so as to not load samlify unnecessarily
await this.loadFromDbAndApplySamlPreferences(false);
if (isSamlLicensedAndEnabled()) {
await this.loadSamlify();
await this.loadFromDbAndApplySamlPreferences(true);
try {
// load preferences first but do not apply so as to not load samlify unnecessarily
await this.loadFromDbAndApplySamlPreferences(false);
if (isSamlLicensedAndEnabled()) {
await this.loadSamlify();
await this.loadFromDbAndApplySamlPreferences(true);
}
} catch (error) {
// If the SAML configuration has been corrupted in the database we'll
// delete the corrupted configuration and enable email logins again.
if (error instanceof InvalidSamlMetadataError || error instanceof SyntaxError) {
this.logger.warn(
`SAML initialization failed because of invalid metadata in database: ${error.message}. IMPORTANT: Disabling SAML and switching to email-based login for all users. Please review your configuration and re-enable SAML.`,
);
await this.reset();
} else {
throw error;
}
}
}
@ -98,7 +112,7 @@ export class SamlService {
validate: async (response: string) => {
const valid = await validateResponse(response);
if (!valid) {
throw new ApplicationError('Invalid SAML response');
throw new InvalidSamlMetadataError();
}
},
});
@ -230,7 +244,7 @@ export class SamlService {
} else if (prefs.metadata) {
const validationResult = await validateMetadata(prefs.metadata);
if (!validationResult) {
throw new ApplicationError('Invalid SAML metadata');
throw new InvalidSamlMetadataError();
}
}
this.getIdentityProviderInstance(true);
@ -371,4 +385,13 @@ export class SamlService {
}
return attributes;
}
/**
* Disables SAML, switches to email based logins and deletes the SAML
* configuration from the database.
*/
async reset() {
await setSamlLoginEnabled(false);
await Container.get(SettingsRepository).delete({ key: SAML_PREFERENCES_DB_KEY });
}
}

View file

@ -5,10 +5,10 @@ import type { AuthProviderType } from '@/databases/entities/auth-identity';
import { SettingsRepository } from '@/databases/repositories/settings.repository';
/**
* Only one authentication method can be active at a time. This function sets the current authentication method
* and saves it to the database.
* SSO methods should only switch to email and then to another method. Email can switch to any method.
* @param authenticationMethod
* Only one authentication method can be active at a time. This function sets
* the current authentication method and saves it to the database.
* SSO methods should only switch to email and then to another method. Email
* can switch to any method.
*/
export async function setCurrentAuthenticationMethod(
authenticationMethod: AuthProviderType,

View file

@ -1,6 +1,5 @@
import { GlobalConfig } from '@n8n/config';
import { type Workflow, type INode, type WorkflowSettings } from 'n8n-workflow';
import { strict as assert } from 'node:assert';
import { Service } from 'typedi';
import type { Project } from '@/databases/entities/project';
@ -68,11 +67,9 @@ export class SubworkflowPolicyChecker {
const owner = await this.ownershipService.getPersonalProjectOwnerCached(subworkflowProject.id);
assert(owner !== null); // only `null` if not personal
return {
hasReadAccess,
ownerName: owner.firstName + ' ' + owner.lastName,
ownerName: owner ? owner.firstName + ' ' + owner.lastName : 'No owner (team project)',
};
}

View file

@ -26,7 +26,7 @@ import { mockInstance } from '../../shared/mocking';
config.set('executions.mode', 'queue');
config.set('binaryDataManager.availableModes', 'filesystem');
Container.get(TaskRunnersConfig).disabled = false;
Container.get(TaskRunnersConfig).enabled = true;
mockInstance(LoadNodesAndCredentials);
const binaryDataService = mockInstance(BinaryDataService);
const externalHooks = mockInstance(ExternalHooks);

View file

@ -18,14 +18,14 @@ describe('TaskRunnerModule in external mode', () => {
describe('start', () => {
it('should throw if the task runner is disabled', async () => {
runnerConfig.disabled = true;
runnerConfig.enabled = false;
// Act
await expect(module.start()).rejects.toThrow('Task runner is disabled');
});
it('should start the task runner', async () => {
runnerConfig.disabled = false;
runnerConfig.enabled = true;
// Act
await module.start();

View file

@ -18,14 +18,14 @@ describe('TaskRunnerModule in internal_childprocess mode', () => {
describe('start', () => {
it('should throw if the task runner is disabled', async () => {
runnerConfig.disabled = true;
runnerConfig.enabled = false;
// Act
await expect(module.start()).rejects.toThrow('Task runner is disabled');
});
it('should start the task runner', async () => {
runnerConfig.disabled = false;
runnerConfig.enabled = true;
// Act
await module.start();

View file

@ -10,7 +10,7 @@ import { retryUntil } from '@test-integration/retry-until';
describe('TaskRunnerProcess', () => {
const authToken = 'token';
const runnerConfig = Container.get(TaskRunnersConfig);
runnerConfig.disabled = false;
runnerConfig.enabled = true;
runnerConfig.mode = 'internal_childprocess';
runnerConfig.authToken = authToken;
runnerConfig.port = 0; // Use any port

View file

@ -111,6 +111,7 @@ import type {
AiEvent,
ISupplyDataFunctions,
WebhookType,
SchedulingFunctions,
} from 'n8n-workflow';
import {
NodeConnectionType,
@ -175,6 +176,7 @@ import {
TriggerContext,
WebhookContext,
} from './node-execution-context';
import { ScheduledTaskManager } from './ScheduledTaskManager';
import { getSecretsProxy } from './Secrets';
import { SSHClientsManager } from './SSHClientsManager';
@ -3028,7 +3030,7 @@ const executionCancellationFunctions = (
},
});
const getRequestHelperFunctions = (
export const getRequestHelperFunctions = (
workflow: Workflow,
node: INode,
additionalData: IWorkflowExecuteAdditionalData,
@ -3348,11 +3350,19 @@ const getRequestHelperFunctions = (
};
};
const getSSHTunnelFunctions = (): SSHTunnelFunctions => ({
export const getSSHTunnelFunctions = (): SSHTunnelFunctions => ({
getSSHClient: async (credentials) =>
await Container.get(SSHClientsManager).getClient(credentials),
});
export const getSchedulingFunctions = (workflow: Workflow): SchedulingFunctions => {
const scheduledTaskManager = Container.get(ScheduledTaskManager);
return {
registerCron: (cronExpression, onTick) =>
scheduledTaskManager.registerCron(workflow, cronExpression, onTick),
};
};
const getAllowedPaths = () => {
const restrictFileAccessTo = process.env[RESTRICT_FILE_ACCESS_TO];
if (!restrictFileAccessTo) {
@ -3419,7 +3429,7 @@ export function isFilePathBlocked(filePath: string): boolean {
return false;
}
const getFileSystemHelperFunctions = (node: INode): FileSystemHelperFunctions => ({
export const getFileSystemHelperFunctions = (node: INode): FileSystemHelperFunctions => ({
async createReadStream(filePath) {
try {
await fsAccess(filePath);
@ -3455,7 +3465,7 @@ const getFileSystemHelperFunctions = (node: INode): FileSystemHelperFunctions =>
},
});
const getNodeHelperFunctions = (
export const getNodeHelperFunctions = (
{ executionId }: IWorkflowExecuteAdditionalData,
workflowId: string,
): NodeHelperFunctions => ({
@ -3463,7 +3473,7 @@ const getNodeHelperFunctions = (
await copyBinaryFile(workflowId, executionId!, filePath, fileName, mimeType),
});
const getBinaryHelperFunctions = (
export const getBinaryHelperFunctions = (
{ executionId }: IWorkflowExecuteAdditionalData,
workflowId: string,
): BinaryHelperFunctions => ({
@ -3481,7 +3491,7 @@ const getBinaryHelperFunctions = (
},
});
const getCheckProcessedHelperFunctions = (
export const getCheckProcessedHelperFunctions = (
workflow: Workflow,
node: INode,
): DeduplicationHelperFunctions => ({

View file

@ -28,13 +28,13 @@ import {
continueOnFail,
getAdditionalKeys,
getBinaryDataBuffer,
getBinaryHelperFunctions,
getCredentials,
getNodeParameter,
getRequestHelperFunctions,
returnJsonArray,
} from '@/NodeExecuteFunctions';
import { BinaryHelpers } from './helpers/binary-helpers';
import { RequestHelpers } from './helpers/request-helpers';
import { NodeExecutionContext } from './node-execution-context';
// todo simplify
@ -66,8 +66,14 @@ export class ExecuteSingleContext extends NodeExecutionContext implements IExecu
this.helpers = {
createDeferredPromise,
returnJsonArray,
...new BinaryHelpers(workflow, additionalData).exported,
...new RequestHelpers(this, workflow, node, additionalData).exported,
...getRequestHelperFunctions(
workflow,
node,
additionalData,
runExecutionData,
connectionInputData,
),
...getBinaryHelperFunctions(additionalData, workflow.id),
assertBinaryData: (propertyName, inputIndex = 0) =>
assertBinaryData(inputData, node, itemIndex, propertyName, inputIndex),

View file

@ -1,136 +0,0 @@
import FileType from 'file-type';
import { IncomingMessage, type ClientRequest } from 'http';
import { mock } from 'jest-mock-extended';
import type { Workflow, IWorkflowExecuteAdditionalData, IBinaryData } from 'n8n-workflow';
import type { Socket } from 'net';
import { Container } from 'typedi';
import { BinaryDataService } from '@/BinaryData/BinaryData.service';
import { BinaryHelpers } from '../binary-helpers';
jest.mock('file-type');
describe('BinaryHelpers', () => {
let binaryDataService = mock<BinaryDataService>();
Container.set(BinaryDataService, binaryDataService);
const workflow = mock<Workflow>({ id: '123' });
const additionalData = mock<IWorkflowExecuteAdditionalData>({ executionId: '456' });
const binaryHelpers = new BinaryHelpers(workflow, additionalData);
beforeEach(() => {
jest.clearAllMocks();
binaryDataService.store.mockImplementation(
async (_workflowId, _executionId, _buffer, value) => value,
);
});
describe('getBinaryPath', () => {
it('should call getPath method of BinaryDataService', () => {
binaryHelpers.getBinaryPath('mock-binary-data-id');
expect(binaryDataService.getPath).toHaveBeenCalledWith('mock-binary-data-id');
});
});
describe('getBinaryMetadata', () => {
it('should call getMetadata method of BinaryDataService', async () => {
await binaryHelpers.getBinaryMetadata('mock-binary-data-id');
expect(binaryDataService.getMetadata).toHaveBeenCalledWith('mock-binary-data-id');
});
});
describe('getBinaryStream', () => {
it('should call getStream method of BinaryDataService', async () => {
await binaryHelpers.getBinaryStream('mock-binary-data-id');
expect(binaryDataService.getAsStream).toHaveBeenCalledWith('mock-binary-data-id', undefined);
});
});
describe('prepareBinaryData', () => {
it('should guess the mime type and file extension if not provided', async () => {
const buffer = Buffer.from('test');
const fileTypeData = { mime: 'application/pdf', ext: 'pdf' };
(FileType.fromBuffer as jest.Mock).mockResolvedValue(fileTypeData);
const binaryData = await binaryHelpers.prepareBinaryData(buffer);
expect(binaryData.mimeType).toEqual('application/pdf');
expect(binaryData.fileExtension).toEqual('pdf');
expect(binaryData.fileType).toEqual('pdf');
expect(binaryData.fileName).toBeUndefined();
expect(binaryData.directory).toBeUndefined();
expect(binaryDataService.store).toHaveBeenCalledWith(
workflow.id,
additionalData.executionId!,
buffer,
binaryData,
);
});
it('should use the provided mime type and file extension if provided', async () => {
const buffer = Buffer.from('test');
const mimeType = 'application/octet-stream';
const binaryData = await binaryHelpers.prepareBinaryData(buffer, undefined, mimeType);
expect(binaryData.mimeType).toEqual(mimeType);
expect(binaryData.fileExtension).toEqual('bin');
expect(binaryData.fileType).toBeUndefined();
expect(binaryData.fileName).toBeUndefined();
expect(binaryData.directory).toBeUndefined();
expect(binaryDataService.store).toHaveBeenCalledWith(
workflow.id,
additionalData.executionId!,
buffer,
binaryData,
);
});
const mockSocket = mock<Socket>({ readableHighWaterMark: 0 });
it('should use the contentDisposition.filename, responseUrl, and contentType properties to set the fileName, directory, and mimeType properties of the binaryData object', async () => {
const incomingMessage = new IncomingMessage(mockSocket);
incomingMessage.contentDisposition = { filename: 'test.txt', type: 'attachment' };
incomingMessage.contentType = 'text/plain';
incomingMessage.responseUrl = 'https://example.com/test.txt';
const binaryData = await binaryHelpers.prepareBinaryData(incomingMessage);
expect(binaryData.fileName).toEqual('test.txt');
expect(binaryData.fileType).toEqual('text');
expect(binaryData.directory).toBeUndefined();
expect(binaryData.mimeType).toEqual('text/plain');
expect(binaryData.fileExtension).toEqual('txt');
});
it('should use the req.path property to set the fileName property of the binaryData object if contentDisposition.filename and responseUrl are not provided', async () => {
const incomingMessage = new IncomingMessage(mockSocket);
incomingMessage.contentType = 'text/plain';
incomingMessage.req = mock<ClientRequest>({ path: '/test.txt' });
const binaryData = await binaryHelpers.prepareBinaryData(incomingMessage);
expect(binaryData.fileName).toEqual('test.txt');
expect(binaryData.directory).toBeUndefined();
expect(binaryData.mimeType).toEqual('text/plain');
expect(binaryData.fileExtension).toEqual('txt');
});
});
describe('setBinaryDataBuffer', () => {
it('should call store method of BinaryDataService', async () => {
const binaryData = mock<IBinaryData>();
const bufferOrStream = mock<Buffer>();
await binaryHelpers.setBinaryDataBuffer(binaryData, bufferOrStream);
expect(binaryDataService.store).toHaveBeenCalledWith(
workflow.id,
additionalData.executionId,
bufferOrStream,
binaryData,
);
});
});
});

View file

@ -1,33 +0,0 @@
import { mock } from 'jest-mock-extended';
import type { Workflow } from 'n8n-workflow';
import { Container } from 'typedi';
import { ScheduledTaskManager } from '@/ScheduledTaskManager';
import { SchedulingHelpers } from '../scheduling-helpers';
describe('SchedulingHelpers', () => {
const scheduledTaskManager = mock<ScheduledTaskManager>();
Container.set(ScheduledTaskManager, scheduledTaskManager);
const workflow = mock<Workflow>();
const schedulingHelpers = new SchedulingHelpers(workflow);
beforeEach(() => {
jest.clearAllMocks();
});
describe('registerCron', () => {
it('should call registerCron method of ScheduledTaskManager', () => {
const cronExpression = '* * * * * *';
const onTick = jest.fn();
schedulingHelpers.registerCron(cronExpression, onTick);
expect(scheduledTaskManager.registerCron).toHaveBeenCalledWith(
workflow,
cronExpression,
onTick,
);
});
});
});

View file

@ -1,32 +0,0 @@
import { mock } from 'jest-mock-extended';
import type { SSHCredentials } from 'n8n-workflow';
import type { Client } from 'ssh2';
import { Container } from 'typedi';
import { SSHClientsManager } from '@/SSHClientsManager';
import { SSHTunnelHelpers } from '../ssh-tunnel-helpers';
describe('SSHTunnelHelpers', () => {
const sshClientsManager = mock<SSHClientsManager>();
Container.set(SSHClientsManager, sshClientsManager);
const sshTunnelHelpers = new SSHTunnelHelpers();
beforeEach(() => {
jest.clearAllMocks();
});
describe('getSSHClient', () => {
const credentials = mock<SSHCredentials>();
it('should call SSHClientsManager.getClient with the given credentials', async () => {
const mockClient = mock<Client>();
sshClientsManager.getClient.mockResolvedValue(mockClient);
const client = await sshTunnelHelpers.getSSHClient(credentials);
expect(sshClientsManager.getClient).toHaveBeenCalledWith(credentials);
expect(client).toBe(mockClient);
});
});
});

View file

@ -1,148 +0,0 @@
import FileType from 'file-type';
import { IncomingMessage } from 'http';
import MimeTypes from 'mime-types';
import { ApplicationError, fileTypeFromMimeType } from 'n8n-workflow';
import type {
BinaryHelperFunctions,
IWorkflowExecuteAdditionalData,
Workflow,
IBinaryData,
} from 'n8n-workflow';
import path from 'path';
import type { Readable } from 'stream';
import Container from 'typedi';
import { BinaryDataService } from '@/BinaryData/BinaryData.service';
import { binaryToBuffer } from '@/BinaryData/utils';
// eslint-disable-next-line import/no-cycle
import { binaryToString } from '@/NodeExecuteFunctions';
export class BinaryHelpers {
private readonly binaryDataService = Container.get(BinaryDataService);
constructor(
private readonly workflow: Workflow,
private readonly additionalData: IWorkflowExecuteAdditionalData,
) {}
get exported(): BinaryHelperFunctions {
return {
getBinaryPath: this.getBinaryPath.bind(this),
getBinaryMetadata: this.getBinaryMetadata.bind(this),
getBinaryStream: this.getBinaryStream.bind(this),
binaryToBuffer,
binaryToString,
prepareBinaryData: this.prepareBinaryData.bind(this),
setBinaryDataBuffer: this.setBinaryDataBuffer.bind(this),
copyBinaryFile: this.copyBinaryFile.bind(this),
};
}
getBinaryPath(binaryDataId: string) {
return this.binaryDataService.getPath(binaryDataId);
}
async getBinaryMetadata(binaryDataId: string) {
return await this.binaryDataService.getMetadata(binaryDataId);
}
async getBinaryStream(binaryDataId: string, chunkSize?: number) {
return await this.binaryDataService.getAsStream(binaryDataId, chunkSize);
}
// eslint-disable-next-line complexity
async prepareBinaryData(binaryData: Buffer | Readable, filePath?: string, mimeType?: string) {
let fileExtension: string | undefined;
if (binaryData instanceof IncomingMessage) {
if (!filePath) {
try {
const { responseUrl } = binaryData;
filePath =
binaryData.contentDisposition?.filename ??
((responseUrl && new URL(responseUrl).pathname) ?? binaryData.req?.path)?.slice(1);
} catch {}
}
if (!mimeType) {
mimeType = binaryData.contentType;
}
}
if (!mimeType) {
// If no mime type is given figure it out
if (filePath) {
// Use file path to guess mime type
const mimeTypeLookup = MimeTypes.lookup(filePath);
if (mimeTypeLookup) {
mimeType = mimeTypeLookup;
}
}
if (!mimeType) {
if (Buffer.isBuffer(binaryData)) {
// Use buffer to guess mime type
const fileTypeData = await FileType.fromBuffer(binaryData);
if (fileTypeData) {
mimeType = fileTypeData.mime;
fileExtension = fileTypeData.ext;
}
} else if (binaryData instanceof IncomingMessage) {
mimeType = binaryData.headers['content-type'];
} else {
// TODO: detect filetype from other kind of streams
}
}
}
if (!fileExtension && mimeType) {
fileExtension = MimeTypes.extension(mimeType) || undefined;
}
if (!mimeType) {
// Fall back to text
mimeType = 'text/plain';
}
const returnData: IBinaryData = {
mimeType,
fileType: fileTypeFromMimeType(mimeType),
fileExtension,
data: '',
};
if (filePath) {
if (filePath.includes('?')) {
// Remove maybe present query parameters
filePath = filePath.split('?').shift();
}
const filePathParts = path.parse(filePath as string);
if (filePathParts.dir !== '') {
returnData.directory = filePathParts.dir;
}
returnData.fileName = filePathParts.base;
// Remove the dot
const extractedFileExtension = filePathParts.ext.slice(1);
if (extractedFileExtension) {
returnData.fileExtension = extractedFileExtension;
}
}
return await this.setBinaryDataBuffer(returnData, binaryData);
}
async setBinaryDataBuffer(binaryData: IBinaryData, bufferOrStream: Buffer | Readable) {
return await this.binaryDataService.store(
this.workflow.id,
this.additionalData.executionId!,
bufferOrStream,
binaryData,
);
}
async copyBinaryFile(): Promise<never> {
throw new ApplicationError('`copyBinaryFile` has been removed. Please upgrade this node.');
}
}

View file

@ -1,381 +0,0 @@
import { createHash } from 'crypto';
import { pick } from 'lodash';
import { jsonParse, NodeOperationError, sleep } from 'n8n-workflow';
import type {
RequestHelperFunctions,
IAdditionalCredentialOptions,
IAllExecuteFunctions,
IExecuteData,
IHttpRequestOptions,
IN8nHttpFullResponse,
IN8nHttpResponse,
INode,
INodeExecutionData,
IOAuth2Options,
IRequestOptions,
IRunExecutionData,
IWorkflowDataProxyAdditionalKeys,
IWorkflowExecuteAdditionalData,
NodeParameterValueType,
PaginationOptions,
Workflow,
WorkflowExecuteMode,
} from 'n8n-workflow';
import { Readable } from 'stream';
// eslint-disable-next-line import/no-cycle
import {
applyPaginationRequestData,
binaryToString,
httpRequest,
httpRequestWithAuthentication,
proxyRequestToAxios,
requestOAuth1,
requestOAuth2,
requestWithAuthentication,
validateUrl,
} from '@/NodeExecuteFunctions';
export class RequestHelpers {
constructor(
private readonly context: IAllExecuteFunctions,
private readonly workflow: Workflow,
private readonly node: INode,
private readonly additionalData: IWorkflowExecuteAdditionalData,
private readonly runExecutionData: IRunExecutionData | null = null,
private readonly connectionInputData: INodeExecutionData[] = [],
) {}
get exported(): RequestHelperFunctions {
return {
httpRequest,
httpRequestWithAuthentication: this.httpRequestWithAuthentication.bind(this),
requestWithAuthenticationPaginated: this.requestWithAuthenticationPaginated.bind(this),
request: this.request.bind(this),
requestWithAuthentication: this.requestWithAuthentication.bind(this),
requestOAuth1: this.requestOAuth1.bind(this),
requestOAuth2: this.requestOAuth2.bind(this),
};
}
get httpRequest() {
return httpRequest;
}
async httpRequestWithAuthentication(
credentialsType: string,
requestOptions: IHttpRequestOptions,
additionalCredentialOptions?: IAdditionalCredentialOptions,
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await httpRequestWithAuthentication.call(
this.context,
credentialsType,
requestOptions,
this.workflow,
this.node,
this.additionalData,
additionalCredentialOptions,
);
}
// eslint-disable-next-line complexity
async requestWithAuthenticationPaginated(
requestOptions: IRequestOptions,
itemIndex: number,
paginationOptions: PaginationOptions,
credentialsType?: string,
additionalCredentialOptions?: IAdditionalCredentialOptions,
): Promise<unknown[]> {
const responseData = [];
if (!requestOptions.qs) {
requestOptions.qs = {};
}
requestOptions.resolveWithFullResponse = true;
requestOptions.simple = false;
let tempResponseData: IN8nHttpFullResponse;
let makeAdditionalRequest: boolean;
let paginateRequestData: PaginationOptions['request'];
const runIndex = 0;
const additionalKeys = {
$request: requestOptions,
$response: {} as IN8nHttpFullResponse,
$version: this.node.typeVersion,
$pageCount: 0,
};
const executeData: IExecuteData = {
data: {},
node: this.node,
source: null,
};
const hashData = {
identicalCount: 0,
previousLength: 0,
previousHash: '',
};
do {
paginateRequestData = this.getResolvedValue(
paginationOptions.request as unknown as NodeParameterValueType,
itemIndex,
runIndex,
executeData,
additionalKeys,
false,
) as object as PaginationOptions['request'];
const tempRequestOptions = applyPaginationRequestData(requestOptions, paginateRequestData);
if (!validateUrl(tempRequestOptions.uri as string)) {
throw new NodeOperationError(
this.node,
`'${paginateRequestData.url}' is not a valid URL.`,
{
itemIndex,
runIndex,
type: 'invalid_url',
},
);
}
if (credentialsType) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
tempResponseData = await this.requestWithAuthentication(
credentialsType,
tempRequestOptions,
additionalCredentialOptions,
);
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
tempResponseData = await this.request(tempRequestOptions);
}
const newResponse: IN8nHttpFullResponse = Object.assign(
{
body: {},
headers: {},
statusCode: 0,
},
pick(tempResponseData, ['body', 'headers', 'statusCode']),
);
let contentBody: Exclude<IN8nHttpResponse, Buffer>;
if (newResponse.body instanceof Readable && paginationOptions.binaryResult !== true) {
// Keep the original string version that we can use it to hash if needed
contentBody = await binaryToString(newResponse.body as Buffer | Readable);
const responseContentType = newResponse.headers['content-type']?.toString() ?? '';
if (responseContentType.includes('application/json')) {
newResponse.body = jsonParse(contentBody, { fallbackValue: {} });
} else {
newResponse.body = contentBody;
}
tempResponseData.__bodyResolved = true;
tempResponseData.body = newResponse.body;
} else {
contentBody = newResponse.body;
}
if (paginationOptions.binaryResult !== true || tempResponseData.headers.etag) {
// If the data is not binary (and so not a stream), or an etag is present,
// we check via etag or hash if identical data is received
let contentLength = 0;
if ('content-length' in tempResponseData.headers) {
contentLength = parseInt(tempResponseData.headers['content-length'] as string) || 0;
}
if (hashData.previousLength === contentLength) {
let hash: string;
if (tempResponseData.headers.etag) {
// If an etag is provided, we use it as "hash"
hash = tempResponseData.headers.etag as string;
} else {
// If there is no etag, we calculate a hash from the data in the body
if (typeof contentBody !== 'string') {
contentBody = JSON.stringify(contentBody);
}
hash = createHash('md5').update(contentBody).digest('base64');
}
if (hashData.previousHash === hash) {
hashData.identicalCount += 1;
if (hashData.identicalCount > 2) {
// Length was identical 5x and hash 3x
throw new NodeOperationError(
this.node,
'The returned response was identical 5x, so requests got stopped',
{
itemIndex,
description:
'Check if "Pagination Completed When" has been configured correctly.',
},
);
}
} else {
hashData.identicalCount = 0;
}
hashData.previousHash = hash;
} else {
hashData.identicalCount = 0;
}
hashData.previousLength = contentLength;
}
responseData.push(tempResponseData);
additionalKeys.$response = newResponse;
additionalKeys.$pageCount = additionalKeys.$pageCount + 1;
const maxRequests = this.getResolvedValue(
paginationOptions.maxRequests,
itemIndex,
runIndex,
executeData,
additionalKeys,
false,
) as number;
if (maxRequests && additionalKeys.$pageCount >= maxRequests) {
break;
}
makeAdditionalRequest = this.getResolvedValue(
paginationOptions.continue,
itemIndex,
runIndex,
executeData,
additionalKeys,
false,
) as boolean;
if (makeAdditionalRequest) {
if (paginationOptions.requestInterval) {
const requestInterval = this.getResolvedValue(
paginationOptions.requestInterval,
itemIndex,
runIndex,
executeData,
additionalKeys,
false,
) as number;
await sleep(requestInterval);
}
if (tempResponseData.statusCode < 200 || tempResponseData.statusCode >= 300) {
// We have it configured to let all requests pass no matter the response code
// via "requestOptions.simple = false" to not by default fail if it is for example
// configured to stop on 404 response codes. For that reason we have to throw here
// now an error manually if the response code is not a success one.
let data = tempResponseData.body;
if (data instanceof Readable && paginationOptions.binaryResult !== true) {
data = await binaryToString(data as Buffer | Readable);
} else if (typeof data === 'object') {
data = JSON.stringify(data);
}
throw Object.assign(new Error(`${tempResponseData.statusCode} - "${data?.toString()}"`), {
statusCode: tempResponseData.statusCode,
error: data,
isAxiosError: true,
response: {
headers: tempResponseData.headers,
status: tempResponseData.statusCode,
statusText: tempResponseData.statusMessage,
},
});
}
}
} while (makeAdditionalRequest);
return responseData;
}
async request(uriOrObject: string | IRequestOptions, options?: IRequestOptions) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await proxyRequestToAxios(
this.workflow,
this.additionalData,
this.node,
uriOrObject,
options,
);
}
async requestWithAuthentication(
credentialsType: string,
requestOptions: IRequestOptions,
additionalCredentialOptions?: IAdditionalCredentialOptions,
itemIndex?: number,
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await requestWithAuthentication.call(
this.context,
credentialsType,
requestOptions,
this.workflow,
this.node,
this.additionalData,
additionalCredentialOptions,
itemIndex,
);
}
async requestOAuth1(credentialsType: string, requestOptions: IRequestOptions) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await requestOAuth1.call(this.context, credentialsType, requestOptions);
}
async requestOAuth2(
credentialsType: string,
requestOptions: IRequestOptions,
oAuth2Options?: IOAuth2Options,
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return await requestOAuth2.call(
this.context,
credentialsType,
requestOptions,
this.node,
this.additionalData,
oAuth2Options,
);
}
private getResolvedValue(
parameterValue: NodeParameterValueType,
itemIndex: number,
runIndex: number,
executeData: IExecuteData,
additionalKeys?: IWorkflowDataProxyAdditionalKeys,
returnObjectAsString = false,
): NodeParameterValueType {
const mode: WorkflowExecuteMode = 'internal';
if (
typeof parameterValue === 'object' ||
(typeof parameterValue === 'string' && parameterValue.charAt(0) === '=')
) {
return this.workflow.expression.getParameterValue(
parameterValue,
this.runExecutionData,
runIndex,
itemIndex,
this.node.name,
this.connectionInputData,
mode,
additionalKeys ?? {},
executeData,
returnObjectAsString,
);
}
return parameterValue;
}
}

View file

@ -1,20 +0,0 @@
import type { CronExpression, Workflow, SchedulingFunctions } from 'n8n-workflow';
import { Container } from 'typedi';
import { ScheduledTaskManager } from '@/ScheduledTaskManager';
export class SchedulingHelpers {
private readonly scheduledTaskManager = Container.get(ScheduledTaskManager);
constructor(private readonly workflow: Workflow) {}
get exported(): SchedulingFunctions {
return {
registerCron: this.registerCron.bind(this),
};
}
registerCron(cronExpression: CronExpression, onTick: () => void) {
this.scheduledTaskManager.registerCron(this.workflow, cronExpression, onTick);
}
}

View file

@ -1,18 +0,0 @@
import type { SSHCredentials, SSHTunnelFunctions } from 'n8n-workflow';
import { Container } from 'typedi';
import { SSHClientsManager } from '@/SSHClientsManager';
export class SSHTunnelHelpers {
private readonly sshClientsManager = Container.get(SSHClientsManager);
get exported(): SSHTunnelFunctions {
return {
getSSHClient: this.getSSHClient.bind(this),
};
}
async getSSHClient(credentials: SSHCredentials) {
return await this.sshClientsManager.getClient(credentials);
}
}

View file

@ -21,10 +21,10 @@ import {
getCredentials,
getNodeParameter,
getNodeWebhookUrl,
getRequestHelperFunctions,
getWebhookDescription,
} from '@/NodeExecuteFunctions';
import { RequestHelpers } from './helpers/request-helpers';
import { NodeExecutionContext } from './node-execution-context';
export class HookContext extends NodeExecutionContext implements IHookFunctions {
@ -40,7 +40,7 @@ export class HookContext extends NodeExecutionContext implements IHookFunctions
) {
super(workflow, node, additionalData, mode);
this.helpers = new RequestHelpers(this, workflow, node, additionalData);
this.helpers = getRequestHelperFunctions(workflow, node, additionalData);
}
getActivationMode() {

View file

@ -13,10 +13,14 @@ import type {
import { extractValue } from '@/ExtractValue';
// eslint-disable-next-line import/no-cycle
import { getAdditionalKeys, getCredentials, getNodeParameter } from '@/NodeExecuteFunctions';
import {
getAdditionalKeys,
getCredentials,
getNodeParameter,
getRequestHelperFunctions,
getSSHTunnelFunctions,
} from '@/NodeExecuteFunctions';
import { RequestHelpers } from './helpers/request-helpers';
import { SSHTunnelHelpers } from './helpers/ssh-tunnel-helpers';
import { NodeExecutionContext } from './node-execution-context';
export class LoadOptionsContext extends NodeExecutionContext implements ILoadOptionsFunctions {
@ -31,8 +35,8 @@ export class LoadOptionsContext extends NodeExecutionContext implements ILoadOpt
super(workflow, node, additionalData, 'internal');
this.helpers = {
...new RequestHelpers(this, workflow, node, additionalData).exported,
...new SSHTunnelHelpers().exported,
...getSSHTunnelFunctions(),
...getRequestHelperFunctions(workflow, node, additionalData),
};
}

View file

@ -16,14 +16,14 @@ import { ApplicationError, createDeferredPromise } from 'n8n-workflow';
// eslint-disable-next-line import/no-cycle
import {
getAdditionalKeys,
getBinaryHelperFunctions,
getCredentials,
getNodeParameter,
getRequestHelperFunctions,
getSchedulingFunctions,
returnJsonArray,
} from '@/NodeExecuteFunctions';
import { BinaryHelpers } from './helpers/binary-helpers';
import { RequestHelpers } from './helpers/request-helpers';
import { SchedulingHelpers } from './helpers/scheduling-helpers';
import { NodeExecutionContext } from './node-execution-context';
const throwOnEmit = () => {
@ -51,9 +51,9 @@ export class PollContext extends NodeExecutionContext implements IPollFunctions
this.helpers = {
createDeferredPromise,
returnJsonArray,
...new BinaryHelpers(workflow, additionalData).exported,
...new RequestHelpers(this, workflow, node, additionalData).exported,
...new SchedulingHelpers(workflow).exported,
...getRequestHelperFunctions(workflow, node, additionalData),
...getBinaryHelperFunctions(additionalData, workflow.id),
...getSchedulingFunctions(workflow),
};
}

View file

@ -16,15 +16,15 @@ import { ApplicationError, createDeferredPromise } from 'n8n-workflow';
// eslint-disable-next-line import/no-cycle
import {
getAdditionalKeys,
getBinaryHelperFunctions,
getCredentials,
getNodeParameter,
getRequestHelperFunctions,
getSchedulingFunctions,
getSSHTunnelFunctions,
returnJsonArray,
} from '@/NodeExecuteFunctions';
import { BinaryHelpers } from './helpers/binary-helpers';
import { RequestHelpers } from './helpers/request-helpers';
import { SchedulingHelpers } from './helpers/scheduling-helpers';
import { SSHTunnelHelpers } from './helpers/ssh-tunnel-helpers';
import { NodeExecutionContext } from './node-execution-context';
const throwOnEmit = () => {
@ -52,10 +52,10 @@ export class TriggerContext extends NodeExecutionContext implements ITriggerFunc
this.helpers = {
createDeferredPromise,
returnJsonArray,
...new BinaryHelpers(workflow, additionalData).exported,
...new RequestHelpers(this, workflow, node, additionalData).exported,
...new SchedulingHelpers(workflow).exported,
...new SSHTunnelHelpers().exported,
...getSSHTunnelFunctions(),
...getRequestHelperFunctions(workflow, node, additionalData),
...getBinaryHelperFunctions(additionalData, workflow.id),
...getSchedulingFunctions(workflow),
};
}

View file

@ -24,15 +24,15 @@ import { ApplicationError, createDeferredPromise } from 'n8n-workflow';
import {
copyBinaryFile,
getAdditionalKeys,
getBinaryHelperFunctions,
getCredentials,
getInputConnectionData,
getNodeParameter,
getNodeWebhookUrl,
getRequestHelperFunctions,
returnJsonArray,
} from '@/NodeExecuteFunctions';
import { BinaryHelpers } from './helpers/binary-helpers';
import { RequestHelpers } from './helpers/request-helpers';
import { NodeExecutionContext } from './node-execution-context';
export class WebhookContext extends NodeExecutionContext implements IWebhookFunctions {
@ -54,8 +54,8 @@ export class WebhookContext extends NodeExecutionContext implements IWebhookFunc
this.helpers = {
createDeferredPromise,
returnJsonArray,
...new BinaryHelpers(workflow, additionalData).exported,
...new RequestHelpers(this, workflow, node, additionalData).exported,
...getRequestHelperFunctions(workflow, node, additionalData),
...getBinaryHelperFunctions(additionalData, workflow.id),
};
this.nodeHelpers = {

View file

@ -1,14 +1,14 @@
<script lang="ts" setup>
<script lang="ts" setup generic="Value extends string">
import RadioButton from './RadioButton.vue';
interface RadioOption {
label: string;
value: string;
value: Value;
disabled?: boolean;
}
interface RadioButtonsProps {
modelValue?: string;
modelValue?: Value;
options?: RadioOption[];
/** @default medium */
size?: 'small' | 'medium';
@ -22,11 +22,11 @@ const props = withDefaults(defineProps<RadioButtonsProps>(), {
});
const emit = defineEmits<{
'update:modelValue': [value: string, e: MouseEvent];
'update:modelValue': [value: Value, e: MouseEvent];
}>();
const onClick = (
option: { label: string; value: string; disabled?: boolean },
option: { label: string; value: Value; disabled?: boolean },
event: MouseEvent,
) => {
if (props.disabled || option.disabled) {

View file

@ -1,11 +1,11 @@
<script lang="ts" setup>
<script lang="ts" setup generic="Value extends string | number">
import { onMounted, onUnmounted, ref } from 'vue';
import type { RouteLocationRaw } from 'vue-router';
import N8nIcon from '../N8nIcon';
interface TabOptions {
value: string;
value: Value;
label?: string;
icon?: string;
href?: string;
@ -15,7 +15,7 @@ interface TabOptions {
}
interface TabsProps {
modelValue?: string;
modelValue?: Value;
options?: TabOptions[];
}
@ -56,12 +56,12 @@ onUnmounted(() => {
});
const emit = defineEmits<{
tooltipClick: [tab: string, e: MouseEvent];
'update:modelValue': [tab: string];
tooltipClick: [tab: Value, e: MouseEvent];
'update:modelValue': [tab: Value];
}>();
const handleTooltipClick = (tab: string, event: MouseEvent) => emit('tooltipClick', tab, event);
const handleTabClick = (tab: string) => emit('update:modelValue', tab);
const handleTooltipClick = (tab: Value, event: MouseEvent) => emit('tooltipClick', tab, event);
const handleTabClick = (tab: Value) => emit('update:modelValue', tab);
const scroll = (left: number) => {
const container = tabs.value;
@ -84,7 +84,7 @@ const scrollRight = () => scroll(50);
<div ref="tabs" :class="$style.tabs">
<div
v-for="option in options"
:id="option.value"
:id="option.value.toString()"
:key="option.value"
:class="{ [$style.alignRight]: option.align === 'right' }"
>

View file

@ -7,6 +7,7 @@ export default {
component: N8nTree,
};
// @ts-expect-error Storybook incorrect slot types
export const Default: StoryFn = (args, { argTypes }) => ({
setup: () => ({ args }),
props: Object.keys(argTypes),

View file

@ -1,19 +1,16 @@
<script lang="ts" setup>
<script lang="ts" setup generic="Value extends unknown = unknown">
import { computed, useCssModule } from 'vue';
interface TreeProps {
value?: Record<string, unknown>;
value?: Record<string, Value>;
path?: Array<string | number>;
depth?: number;
nodeClass?: string;
}
defineSlots<{
[key: string]: (props: {
label?: string;
path?: Array<string | number>;
value?: unknown;
}) => never;
label(props: { label: string; path: Array<string | number> }): never;
value(props: { value: Value }): never;
}>();
defineOptions({ name: 'N8nTree' });
@ -29,11 +26,11 @@ const classes = computed((): Record<string, boolean> => {
return { [props.nodeClass]: !!props.nodeClass, [$style.indent]: props.depth > 0 };
});
const isObject = (data: unknown): data is Record<string, unknown> => {
const isObject = (data: unknown): data is Record<string, Value> => {
return typeof data === 'object' && data !== null;
};
const isSimple = (data: unknown): boolean => {
const isSimple = (data: Value): boolean => {
if (data === null || data === undefined) {
return true;
}
@ -70,16 +67,21 @@ const getPath = (key: string): Array<string | number> => {
<div v-else>
<slot v-if="$slots.label" name="label" :label="label" :path="getPath(label)" />
<span v-else>{{ label }}</span>
<n8n-tree
<N8nTree
v-if="isObject(value[label])"
:path="getPath(label)"
:depth="depth + 1"
:value="value[label] as Record<string, unknown>"
:value="value[label]"
:node-class="nodeClass"
>
<template v-for="(_, name) in $slots" #[name]="data">
<slot :name="name" v-bind="data"></slot>
<template v-if="$slots.label" #label="data">
<slot name="label" v-bind="data" />
</template>
</n8n-tree>
<template v-if="$slots.value" #value="data">
<slot name="value" v-bind="data" />
</template>
</N8nTree>
</div>
</div>
</div>

View file

@ -1130,8 +1130,8 @@ export interface IInviteResponse {
error?: string;
}
export interface ITab {
value: string | number;
export interface ITab<Value extends string | number = string | number> {
value: Value;
label?: string;
href?: string;
icon?: string;

View file

@ -1,5 +1,5 @@
<script lang="ts">
import type { INodeUi } from '@/Interface';
<script setup lang="ts">
import { useI18n } from '@/composables/useI18n';
import {
CRON_NODE_TYPE,
INTERVAL_NODE_TYPE,
@ -10,331 +10,326 @@ import { useNDVStore } from '@/stores/ndv.store';
import { useNodeTypesStore } from '@/stores/nodeTypes.store';
import { useUIStore } from '@/stores/ui.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import type {
IConnectedNode,
INodeInputConfiguration,
INodeOutputConfiguration,
INodeTypeDescription,
Workflow,
} from 'n8n-workflow';
import { waitingNodeTooltip } from '@/utils/executionUtils';
import { uniqBy } from 'lodash-es';
import type { INodeInputConfiguration, INodeOutputConfiguration, Workflow } from 'n8n-workflow';
import { NodeConnectionType, NodeHelpers } from 'n8n-workflow';
import { mapStores } from 'pinia';
import { defineComponent, type PropType } from 'vue';
import { computed, ref, watch } from 'vue';
import InputNodeSelect from './InputNodeSelect.vue';
import NodeExecuteButton from './NodeExecuteButton.vue';
import RunData from './RunData.vue';
import WireMeUp from './WireMeUp.vue';
import { waitingNodeTooltip } from '@/utils/executionUtils';
import { useTelemetry } from '@/composables/useTelemetry';
import { N8nRadioButtons, N8nTooltip, N8nText } from 'n8n-design-system';
import { storeToRefs } from 'pinia';
type MappingMode = 'debugging' | 'mapping';
export default defineComponent({
name: 'InputPanel',
components: { RunData, NodeExecuteButton, WireMeUp, InputNodeSelect },
props: {
currentNodeName: {
type: String,
},
runIndex: {
type: Number,
required: true,
},
linkedRuns: {
type: Boolean,
},
workflow: {
type: Object as PropType<Workflow>,
required: true,
},
canLinkRuns: {
type: Boolean,
},
pushRef: {
type: String,
required: true,
},
readOnly: {
type: Boolean,
},
isProductionExecutionPreview: {
type: Boolean,
default: false,
},
isPaneActive: {
type: Boolean,
default: false,
},
},
emits: [
'itemHover',
'tableMounted',
'linkRun',
'unlinkRun',
'runChange',
'search',
'changeInputNode',
'execute',
'activatePane',
],
data() {
return {
showDraggableHintWithDelay: false,
draggableHintShown: false,
inputMode: 'debugging' as MappingMode,
mappedNode: null as string | null,
inputModes: [
{ value: 'mapping', label: this.$locale.baseText('ndv.input.mapping') },
{ value: 'debugging', label: this.$locale.baseText('ndv.input.debugging') },
],
};
},
computed: {
...mapStores(useNodeTypesStore, useNDVStore, useWorkflowsStore, useUIStore),
focusedMappableInput(): string {
return this.ndvStore.focusedMappableInput;
},
isUserOnboarded(): boolean {
return this.ndvStore.isMappingOnboarded;
},
isMappingMode(): boolean {
return this.isActiveNodeConfig && this.inputMode === 'mapping';
},
showDraggableHint(): boolean {
const toIgnore = [
START_NODE_TYPE,
MANUAL_TRIGGER_NODE_TYPE,
CRON_NODE_TYPE,
INTERVAL_NODE_TYPE,
];
if (!this.currentNode || toIgnore.includes(this.currentNode.type)) {
return false;
}
type Props = {
runIndex: number;
workflow: Workflow;
pushRef: string;
currentNodeName?: string;
canLinkRuns?: boolean;
linkedRuns?: boolean;
readOnly?: boolean;
isProductionExecutionPreview?: boolean;
isPaneActive?: boolean;
};
return !!this.focusedMappableInput && !this.isUserOnboarded;
},
isActiveNodeConfig(): boolean {
let inputs = this.activeNodeType?.inputs ?? [];
let outputs = this.activeNodeType?.outputs ?? [];
if (this.activeNode !== null && this.workflow !== null) {
const node = this.workflow.getNode(this.activeNode.name);
inputs = NodeHelpers.getNodeInputs(this.workflow, node!, this.activeNodeType!);
outputs = NodeHelpers.getNodeOutputs(this.workflow, node!, this.activeNodeType!);
} else {
// If we can not figure out the node type we set no outputs
if (!Array.isArray(inputs)) {
inputs = [] as NodeConnectionType[];
}
if (!Array.isArray(outputs)) {
outputs = [] as NodeConnectionType[];
}
}
if (
inputs.length === 0 ||
(inputs.every((input) => this.filterOutConnectionType(input, NodeConnectionType.Main)) &&
outputs.find((output) => this.filterOutConnectionType(output, NodeConnectionType.Main)))
) {
return true;
}
return false;
},
isMappingEnabled(): boolean {
if (this.readOnly) return false;
// Mapping is only enabled in mapping mode for config nodes and if node to map is selected
if (this.isActiveNodeConfig) return this.isMappingMode && this.mappedNode !== null;
return true;
},
isExecutingPrevious(): boolean {
if (!this.workflowRunning) {
return false;
}
const triggeredNode = this.workflowsStore.executedNode;
const executingNode = this.workflowsStore.executingNode;
if (
this.activeNode &&
triggeredNode === this.activeNode.name &&
!this.workflowsStore.isNodeExecuting(this.activeNode.name)
) {
return true;
}
if (executingNode.length || triggeredNode) {
return !!this.parentNodes.find(
(node) => this.workflowsStore.isNodeExecuting(node.name) || node.name === triggeredNode,
);
}
return false;
},
workflowRunning(): boolean {
return this.uiStore.isActionActive['workflowRunning'];
},
activeNode(): INodeUi | null {
return this.ndvStore.activeNode;
},
rootNode(): string {
const workflow = this.workflow;
const rootNodes = workflow.getChildNodes(this.activeNode?.name ?? '', 'ALL');
return rootNodes[0];
},
rootNodesParents() {
const workflow = this.workflow;
const parentNodes = [...workflow.getParentNodes(this.rootNode, NodeConnectionType.Main)]
.reverse()
.map((parent): IConnectedNode => ({ name: parent, depth: 1, indicies: [] }));
return parentNodes;
},
currentNode(): INodeUi | null {
if (this.isActiveNodeConfig) {
// if we're mapping node we want to show the output of the mapped node
if (this.mappedNode) {
return this.workflowsStore.getNodeByName(this.mappedNode);
}
// in debugging mode data does get set manually and is only for debugging
// so we want to force the node to be the active node to make sure we show the correct data
return this.activeNode;
}
return this.workflowsStore.getNodeByName(this.currentNodeName ?? '');
},
connectedCurrentNodeOutputs(): number[] | undefined {
const search = this.parentNodes.find(({ name }) => name === this.currentNodeName);
if (search) {
return search.indicies;
}
return undefined;
},
parentNodes(): IConnectedNode[] {
if (!this.activeNode) {
return [];
}
const nodes = this.workflow.getParentNodesByDepth(this.activeNode.name);
return nodes.filter(
({ name }, i) =>
this.activeNode &&
name !== this.activeNode.name &&
nodes.findIndex((node) => node.name === name) === i,
);
},
currentNodeDepth(): number {
const node = this.parentNodes.find(
(parent) => this.currentNode && parent.name === this.currentNode.name,
);
return node ? node.depth : -1;
},
activeNodeType(): INodeTypeDescription | null {
if (!this.activeNode) return null;
return this.nodeTypesStore.getNodeType(this.activeNode.type, this.activeNode.typeVersion);
},
isMultiInputNode(): boolean {
return this.activeNodeType !== null && this.activeNodeType.inputs.length > 1;
},
waitingMessage(): string {
return waitingNodeTooltip();
},
},
watch: {
inputMode: {
handler(val) {
this.onRunIndexChange(-1);
if (val === 'mapping') {
this.onUnlinkRun();
this.mappedNode = this.rootNodesParents[0]?.name ?? null;
} else {
this.mappedNode = null;
}
},
immediate: true,
},
showDraggableHint(curr: boolean, prev: boolean) {
if (curr && !prev) {
setTimeout(() => {
if (this.draggableHintShown) {
return;
}
this.showDraggableHintWithDelay = this.showDraggableHint;
if (this.showDraggableHintWithDelay) {
this.draggableHintShown = true;
this.$telemetry.track('User viewed data mapping tooltip', {
type: 'unexecuted input pane',
});
}
}, 1000);
} else if (!curr) {
this.showDraggableHintWithDelay = false;
}
},
},
methods: {
filterOutConnectionType(
item: NodeConnectionType | INodeOutputConfiguration | INodeInputConfiguration,
type: NodeConnectionType,
) {
if (!item) return false;
return typeof item === 'string' ? item !== type : item.type !== type;
},
onInputModeChange(val: MappingMode) {
this.inputMode = val;
},
onMappedNodeSelected(val: string) {
this.mappedNode = val;
this.onRunIndexChange(0);
this.onUnlinkRun();
},
onNodeExecute() {
this.$emit('execute');
if (this.activeNode) {
this.$telemetry.track('User clicked ndv button', {
node_type: this.activeNode.type,
workflow_id: this.workflowsStore.workflowId,
push_ref: this.pushRef,
pane: 'input',
type: 'executePrevious',
});
}
},
onRunIndexChange(run: number) {
this.$emit('runChange', run);
},
onLinkRun() {
this.$emit('linkRun');
},
onUnlinkRun() {
this.$emit('unlinkRun');
},
onInputNodeChange(value: string) {
const index = this.parentNodes.findIndex((node) => node.name === value) + 1;
this.$emit('changeInputNode', value, index);
},
onConnectionHelpClick() {
if (this.activeNode) {
this.$telemetry.track('User clicked ndv link', {
node_type: this.activeNode.type,
workflow_id: this.workflowsStore.workflowId,
push_ref: this.pushRef,
pane: 'input',
type: 'not-connected-help',
});
}
},
activatePane() {
this.$emit('activatePane');
},
},
const props = withDefaults(defineProps<Props>(), {
currentNodeName: '',
canLinkRuns: false,
readOnly: false,
isProductionExecutionPreview: false,
isPaneActive: false,
});
const emit = defineEmits<{
itemHover: [
{
outputIndex: number;
itemIndex: number;
} | null,
];
tableMounted: [
{
avgRowHeight: number;
},
];
linkRun: [];
unlinkRun: [];
runChange: [runIndex: number];
search: [search: string];
changeInputNode: [nodeName: string, index: number];
execute: [];
activatePane: [];
}>();
const i18n = useI18n();
const telemetry = useTelemetry();
const showDraggableHintWithDelay = ref(false);
const draggableHintShown = ref(false);
const inputMode = ref<MappingMode>('debugging');
const mappedNode = ref<string | null>(null);
const inputModes = [
{ value: 'mapping', label: i18n.baseText('ndv.input.mapping') },
{ value: 'debugging', label: i18n.baseText('ndv.input.debugging') },
];
const nodeTypesStore = useNodeTypesStore();
const ndvStore = useNDVStore();
const workflowsStore = useWorkflowsStore();
const uiStore = useUIStore();
const {
activeNode,
focusedMappableInput,
isMappingOnboarded: isUserOnboarded,
} = storeToRefs(ndvStore);
const isMappingMode = computed(() => isActiveNodeConfig.value && inputMode.value === 'mapping');
const showDraggableHint = computed(() => {
const toIgnore = [START_NODE_TYPE, MANUAL_TRIGGER_NODE_TYPE, CRON_NODE_TYPE, INTERVAL_NODE_TYPE];
if (!currentNode.value || toIgnore.includes(currentNode.value.type)) {
return false;
}
return !!focusedMappableInput.value && !isUserOnboarded.value;
});
const isActiveNodeConfig = computed(() => {
let inputs = activeNodeType.value?.inputs ?? [];
let outputs = activeNodeType.value?.outputs ?? [];
if (props.workflow && activeNode.value) {
const node = props.workflow.getNode(activeNode.value.name);
if (node && activeNodeType.value) {
inputs = NodeHelpers.getNodeInputs(props.workflow, node, activeNodeType.value);
outputs = NodeHelpers.getNodeOutputs(props.workflow, node, activeNodeType.value);
}
}
// If we can not figure out the node type we set no outputs
if (!Array.isArray(inputs)) {
inputs = [];
}
if (!Array.isArray(outputs)) {
outputs = [];
}
return (
inputs.length === 0 ||
(inputs.every((input) => filterOutConnectionType(input, NodeConnectionType.Main)) &&
outputs.find((output) => filterOutConnectionType(output, NodeConnectionType.Main)))
);
});
const isMappingEnabled = computed(() => {
if (props.readOnly) return false;
// Mapping is only enabled in mapping mode for config nodes and if node to map is selected
if (isActiveNodeConfig.value) return isMappingMode.value && mappedNode.value !== null;
return true;
});
const isExecutingPrevious = computed(() => {
if (!workflowRunning.value) {
return false;
}
const triggeredNode = workflowsStore.executedNode;
const executingNode = workflowsStore.executingNode;
if (
activeNode.value &&
triggeredNode === activeNode.value.name &&
!workflowsStore.isNodeExecuting(activeNode.value.name)
) {
return true;
}
if (executingNode.length || triggeredNode) {
return !!parentNodes.value.find(
(node) => workflowsStore.isNodeExecuting(node.name) || node.name === triggeredNode,
);
}
return false;
});
const workflowRunning = computed(() => uiStore.isActionActive.workflowRunning);
const rootNode = computed(() => {
if (!activeNode.value) return null;
return props.workflow.getChildNodes(activeNode.value.name, 'ALL').at(0) ?? null;
});
const rootNodesParents = computed(() => {
if (!rootNode.value) return [];
return props.workflow.getParentNodesByDepth(rootNode.value);
});
const currentNode = computed(() => {
if (isActiveNodeConfig.value) {
// if we're mapping node we want to show the output of the mapped node
if (mappedNode.value) {
return workflowsStore.getNodeByName(mappedNode.value);
}
// in debugging mode data does get set manually and is only for debugging
// so we want to force the node to be the active node to make sure we show the correct data
return activeNode.value;
}
return workflowsStore.getNodeByName(props.currentNodeName ?? '');
});
const connectedCurrentNodeOutputs = computed(() => {
const search = parentNodes.value.find(({ name }) => name === props.currentNodeName);
return search?.indicies;
});
const parentNodes = computed(() => {
if (!activeNode.value) {
return [];
}
const parents = props.workflow
.getParentNodesByDepth(activeNode.value.name)
.filter((parent) => parent.name !== activeNode.value?.name);
return uniqBy(parents, (parent) => parent.name);
});
const currentNodeDepth = computed(() => {
const node = parentNodes.value.find(
(parent) => currentNode.value && parent.name === currentNode.value.name,
);
return node?.depth ?? -1;
});
const activeNodeType = computed(() => {
if (!activeNode.value) return null;
return nodeTypesStore.getNodeType(activeNode.value.type, activeNode.value.typeVersion);
});
const waitingMessage = computed(() => waitingNodeTooltip());
watch(
inputMode,
(mode) => {
onRunIndexChange(-1);
if (mode === 'mapping') {
onUnlinkRun();
mappedNode.value = rootNodesParents.value[0]?.name ?? null;
} else {
mappedNode.value = null;
}
},
{ immediate: true },
);
watch(showDraggableHint, (curr, prev) => {
if (curr && !prev) {
setTimeout(() => {
if (draggableHintShown.value) {
return;
}
showDraggableHintWithDelay.value = showDraggableHint.value;
if (showDraggableHintWithDelay.value) {
draggableHintShown.value = true;
telemetry.track('User viewed data mapping tooltip', {
type: 'unexecuted input pane',
});
}
}, 1000);
} else if (!curr) {
showDraggableHintWithDelay.value = false;
}
});
function filterOutConnectionType(
item: NodeConnectionType | INodeOutputConfiguration | INodeInputConfiguration,
type: NodeConnectionType,
) {
if (!item) return false;
return typeof item === 'string' ? item !== type : item.type !== type;
}
function onInputModeChange(val: string) {
inputMode.value = val as MappingMode;
}
function onMappedNodeSelected(val: string) {
mappedNode.value = val;
onRunIndexChange(0);
onUnlinkRun();
}
function onNodeExecute() {
emit('execute');
if (activeNode.value) {
telemetry.track('User clicked ndv button', {
node_type: activeNode.value.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input',
type: 'executePrevious',
});
}
}
function onRunIndexChange(run: number) {
emit('runChange', run);
}
function onLinkRun() {
emit('linkRun');
}
function onUnlinkRun() {
emit('unlinkRun');
}
function onSearch(search: string) {
emit('search', search);
}
function onItemHover(
item: {
outputIndex: number;
itemIndex: number;
} | null,
) {
emit('itemHover', item);
}
function onTableMounted(event: { avgRowHeight: number }) {
emit('tableMounted', event);
}
function onInputNodeChange(value: string) {
const index = parentNodes.value.findIndex((node) => node.name === value) + 1;
emit('changeInputNode', value, index);
}
function onConnectionHelpClick() {
if (activeNode.value) {
telemetry.track('User clicked ndv link', {
node_type: activeNode.value.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input',
type: 'not-connected-help',
});
}
}
function activatePane() {
emit('activatePane');
}
</script>
<template>
@ -358,18 +353,19 @@ export default defineComponent({
pane-type="input"
data-test-id="ndv-input-panel"
@activate-pane="activatePane"
@item-hover="$emit('itemHover', $event)"
@item-hover="onItemHover"
@link-run="onLinkRun"
@unlink-run="onUnlinkRun"
@run-change="onRunIndexChange"
@table-mounted="$emit('tableMounted', $event)"
@search="$emit('search', $event)"
@table-mounted="onTableMounted"
@search="onSearch"
>
<template #header>
<div :class="$style.titleSection">
<span :class="$style.title">{{ $locale.baseText('ndv.input') }}</span>
<n8n-radio-buttons
<N8nRadioButtons
v-if="isActiveNodeConfig && !readOnly"
data-test-id="input-panel-mode"
:options="inputModes"
:model-value="inputMode"
@update:model-value="onInputModeChange"
@ -405,10 +401,10 @@ export default defineComponent({
v-if="(isActiveNodeConfig && rootNode) || parentNodes.length"
:class="$style.noOutputData"
>
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{
<N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.noOutputData.title')
}}</n8n-text>
<n8n-tooltip v-if="!readOnly" :visible="showDraggableHint && showDraggableHintWithDelay">
}}</N8nText>
<N8nTooltip v-if="!readOnly" :visible="showDraggableHint && showDraggableHintWithDelay">
<template #content>
<div
v-n8n-html="
@ -422,25 +418,25 @@ export default defineComponent({
type="secondary"
hide-icon
:transparent="true"
:node-name="isActiveNodeConfig ? rootNode : (currentNodeName ?? '')"
:node-name="(isActiveNodeConfig ? rootNode : currentNodeName) ?? ''"
:label="$locale.baseText('ndv.input.noOutputData.executePrevious')"
telemetry-source="inputs"
data-test-id="execute-previous-node"
@execute="onNodeExecute"
/>
</n8n-tooltip>
<n8n-text v-if="!readOnly" tag="div" size="small">
</N8nTooltip>
<N8nText v-if="!readOnly" tag="div" size="small">
{{ $locale.baseText('ndv.input.noOutputData.hint') }}
</n8n-text>
</N8nText>
</div>
<div v-else :class="$style.notConnected">
<div>
<WireMeUp />
</div>
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{
<N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.notConnected.title')
}}</n8n-text>
<n8n-text tag="div">
}}</N8nText>
<N8nText tag="div">
{{ $locale.baseText('ndv.input.notConnected.message') }}
<a
href="https://docs.n8n.io/workflows/connections/"
@ -449,29 +445,29 @@ export default defineComponent({
>
{{ $locale.baseText('ndv.input.notConnected.learnMore') }}
</a>
</n8n-text>
</N8nText>
</div>
</template>
<template #node-waiting>
<n8n-text :bold="true" color="text-dark" size="large">Waiting for input</n8n-text>
<n8n-text v-n8n-html="waitingMessage"></n8n-text>
<N8nText :bold="true" color="text-dark" size="large">Waiting for input</N8nText>
<N8nText v-n8n-html="waitingMessage"></N8nText>
</template>
<template #no-output-data>
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{
<N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.input.noOutputData')
}}</n8n-text>
}}</N8nText>
</template>
<template #recovered-artificial-output-data>
<div :class="$style.recoveredOutputData">
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{
<N8nText tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('executionDetails.executionFailed.recoveredNodeTitle')
}}</n8n-text>
<n8n-text>
}}</N8nText>
<N8nText>
{{ $locale.baseText('executionDetails.executionFailed.recoveredNodeMessage') }}
</n8n-text>
</N8nText>
</div>
</template>
</RunData>

View file

@ -1,16 +1,13 @@
<script setup lang="ts">
import { computed, onMounted, defineComponent, h } from 'vue';
import type { PropType } from 'vue';
import { computed, onMounted } from 'vue';
import type {
INodeCreateElement,
NodeFilterType,
IUpdateInformation,
ActionCreateElement,
NodeCreateElement,
} from '@/Interface';
import {
HTTP_REQUEST_NODE_TYPE,
REGULAR_NODE_CREATOR_VIEW,
TRIGGER_NODE_CREATOR_VIEW,
CUSTOM_API_CALL_KEY,
OPEN_AI_NODE_MESSAGE_ASSISTANT_TYPE,
@ -30,6 +27,7 @@ import type { IDataObject } from 'n8n-workflow';
import { useTelemetry } from '@/composables/useTelemetry';
import { useI18n } from '@/composables/useI18n';
import { useNodeCreatorStore } from '@/stores/nodeCreator.store';
import OrderSwitcher from './../OrderSwitcher.vue';
const emit = defineEmits<{
nodeTypeSelected: [value: [actionKey: string, nodeName: string] | [nodeName: string]];
@ -212,26 +210,6 @@ function addHttpNode() {
nodeCreatorStore.onActionsCustomAPIClicked({ app_identifier });
}
// Anonymous component to handle triggers and actions rendering order
const OrderSwitcher = defineComponent({
props: {
rootView: {
type: String as PropType<NodeFilterType>,
required: true,
},
},
setup(props, { slots }) {
return () =>
h(
'div',
{},
props.rootView === REGULAR_NODE_CREATOR_VIEW
? [slots.actions?.(), slots.triggers?.()]
: [slots.triggers?.(), slots.actions?.()],
);
},
});
onMounted(() => {
trackActionsView();
});

View file

@ -0,0 +1,21 @@
<script setup lang="ts">
import type { NodeFilterType } from '@/Interface';
import { REGULAR_NODE_CREATOR_VIEW } from '@/constants';
defineProps<{
rootView: NodeFilterType;
}>();
</script>
<template>
<div>
<template v-if="rootView === REGULAR_NODE_CREATOR_VIEW">
<slot name="actions" />
<slot name="triggers" />
</template>
<template v-else>
<slot name="triggers" />
<slot name="actions" />
</template>
</div>
</template>

View file

@ -16,6 +16,14 @@ import { setupServer } from '@/__tests__/server';
import { defaultNodeDescriptions, mockNodes } from '@/__tests__/mocks';
import { cleanupAppModals, createAppModals } from '@/__tests__/utils';
vi.mock('vue-router', () => {
return {
useRouter: () => ({}),
useRoute: () => ({ meta: {} }),
RouterLink: vi.fn(),
};
});
async function createPiniaWithActiveNode() {
const node = mockNodes[0];
const workflow = mock<IWorkflowDb>({

View file

@ -387,7 +387,7 @@ const onWorkflowActivate = () => {
}, 1000);
};
const onOutputItemHover = (e: { itemIndex: number; outputIndex: number }) => {
const onOutputItemHover = (e: { itemIndex: number; outputIndex: number } | null) => {
if (e === null || !activeNode.value || !isPairedItemHoveringEnabled.value) {
ndvStore.setHoveringItem(null);
return;

View file

@ -15,10 +15,11 @@ import { usePinnedData } from '@/composables/usePinnedData';
import { useTelemetry } from '@/composables/useTelemetry';
import { useI18n } from '@/composables/useI18n';
import { waitingNodeTooltip } from '@/utils/executionUtils';
import { N8nRadioButtons, N8nText } from 'n8n-design-system';
// Types
type RunDataRef = InstanceType<typeof RunData> | null;
type RunDataRef = InstanceType<typeof RunData>;
const OUTPUT_TYPE = {
REGULAR: 'regular',
@ -55,7 +56,7 @@ const emit = defineEmits<{
runChange: [number];
activatePane: [];
tableMounted: [{ avgRowHeight: number }];
itemHover: [{ itemIndex: number; outputIndex: number }];
itemHover: [item: { itemIndex: number; outputIndex: number } | null];
search: [string];
openSettings: [];
}>();
@ -87,7 +88,7 @@ const outputTypes = ref([
{ label: i18n.baseText('ndv.output.outType.regular'), value: OUTPUT_TYPE.REGULAR },
{ label: i18n.baseText('ndv.output.outType.logs'), value: OUTPUT_TYPE.LOGS },
]);
const runDataRef = ref<RunDataRef>(null);
const runDataRef = ref<RunDataRef>();
// Computed
@ -127,9 +128,7 @@ const isNodeRunning = computed(() => {
return workflowRunning.value && !!node.value && workflowsStore.isNodeExecuting(node.value.name);
});
const workflowRunning = computed(() => {
return uiStore.isActionActive['workflowRunning'];
});
const workflowRunning = computed(() => uiStore.isActionActive.workflowRunning);
const workflowExecution = computed(() => {
return workflowsStore.getWorkflowExecution;
@ -253,8 +252,8 @@ const onRunIndexChange = (run: number) => {
emit('runChange', run);
};
const onUpdateOutputMode = (outputMode: OutputType) => {
if (outputMode === OUTPUT_TYPE.LOGS) {
const onUpdateOutputMode = (newOutputMode: OutputType) => {
if (newOutputMode === OUTPUT_TYPE.LOGS) {
ndvEventBus.emit('setPositionByName', 'minLeft');
} else {
ndvEventBus.emit('setPositionByName', 'initial');
@ -288,10 +287,10 @@ const activatePane = () => {
:run-index="runIndex"
:linked-runs="linkedRuns"
:can-link-runs="canLinkRuns"
:too-much-data-title="$locale.baseText('ndv.output.tooMuchData.title')"
:no-data-in-branch-message="$locale.baseText('ndv.output.noOutputDataInBranch')"
:too-much-data-title="i18n.baseText('ndv.output.tooMuchData.title')"
:no-data-in-branch-message="i18n.baseText('ndv.output.noOutputDataInBranch')"
:is-executing="isNodeRunning"
:executing-message="$locale.baseText('ndv.output.executing')"
:executing-message="i18n.baseText('ndv.output.executing')"
:push-ref="pushRef"
:block-u-i="blockUI"
:is-production-execution-preview="isProductionExecutionPreview"
@ -310,15 +309,15 @@ const activatePane = () => {
<template #header>
<div :class="$style.titleSection">
<template v-if="hasAiMetadata">
<n8n-radio-buttons
data-test-id="ai-output-mode-select"
<N8nRadioButtons
v-model="outputMode"
data-test-id="ai-output-mode-select"
:options="outputTypes"
@update:model-value="onUpdateOutputMode"
/>
</template>
<span v-else :class="$style.title">
{{ $locale.baseText(outputPanelEditMode.enabled ? 'ndv.output.edit' : 'ndv.output') }}
{{ i18n.baseText(outputPanelEditMode.enabled ? 'ndv.output.edit' : 'ndv.output') }}
</span>
<RunInfo
v-if="hasNodeRun && !pinnedData.hasData.value && runsCount === 1"
@ -331,42 +330,40 @@ const activatePane = () => {
</template>
<template #node-not-run>
<n8n-text v-if="workflowRunning && !isTriggerNode" data-test-id="ndv-output-waiting">{{
$locale.baseText('ndv.output.waitingToRun')
}}</n8n-text>
<n8n-text v-if="!workflowRunning" data-test-id="ndv-output-run-node-hint">
<N8nText v-if="workflowRunning && !isTriggerNode" data-test-id="ndv-output-waiting">{{
i18n.baseText('ndv.output.waitingToRun')
}}</N8nText>
<N8nText v-if="!workflowRunning" data-test-id="ndv-output-run-node-hint">
<template v-if="isSubNodeType">
{{ $locale.baseText('ndv.output.runNodeHintSubNode') }}
{{ i18n.baseText('ndv.output.runNodeHintSubNode') }}
</template>
<template v-else>
{{ $locale.baseText('ndv.output.runNodeHint') }}
{{ i18n.baseText('ndv.output.runNodeHint') }}
<span v-if="canPinData" @click="insertTestData">
<br />
{{ $locale.baseText('generic.or') }}
<n8n-text tag="a" size="medium" color="primary">
{{ $locale.baseText('ndv.output.insertTestData') }}
</n8n-text>
{{ i18n.baseText('generic.or') }}
<N8nText tag="a" size="medium" color="primary">
{{ i18n.baseText('ndv.output.insertTestData') }}
</N8nText>
</span>
</template>
</n8n-text>
</N8nText>
</template>
<template #node-waiting>
<n8n-text :bold="true" color="text-dark" size="large">Waiting for input</n8n-text>
<n8n-text v-n8n-html="waitingNodeTooltip()"></n8n-text>
<N8nText :bold="true" color="text-dark" size="large">Waiting for input</N8nText>
<N8nText v-n8n-html="waitingNodeTooltip()"></N8nText>
</template>
<template #no-output-data>
<n8n-text :bold="true" color="text-dark" size="large">{{
$locale.baseText('ndv.output.noOutputData.title')
}}</n8n-text>
<n8n-text>
{{ $locale.baseText('ndv.output.noOutputData.message') }}
<a @click="openSettings">{{
$locale.baseText('ndv.output.noOutputData.message.settings')
}}</a>
{{ $locale.baseText('ndv.output.noOutputData.message.settingsOption') }}
</n8n-text>
<N8nText :bold="true" color="text-dark" size="large">{{
i18n.baseText('ndv.output.noOutputData.title')
}}</N8nText>
<N8nText>
{{ i18n.baseText('ndv.output.noOutputData.message') }}
<a @click="openSettings">{{ i18n.baseText('ndv.output.noOutputData.message.settings') }}</a>
{{ i18n.baseText('ndv.output.noOutputData.message.settingsOption') }}
</N8nText>
</template>
<template v-if="outputMode === 'logs' && node" #content>
@ -375,12 +372,12 @@ const activatePane = () => {
<template #recovered-artificial-output-data>
<div :class="$style.recoveredOutputData">
<n8n-text tag="div" :bold="true" color="text-dark" size="large">{{
$locale.baseText('executionDetails.executionFailed.recoveredNodeTitle')
}}</n8n-text>
<n8n-text>
{{ $locale.baseText('executionDetails.executionFailed.recoveredNodeMessage') }}
</n8n-text>
<N8nText tag="div" :bold="true" color="text-dark" size="large">{{
i18n.baseText('executionDetails.executionFailed.recoveredNodeTitle')
}}</N8nText>
<N8nText>
{{ i18n.baseText('executionDetails.executionFailed.recoveredNodeMessage') }}
</N8nText>
</div>
</template>

View file

@ -1,16 +1,24 @@
import { waitFor } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import { createTestingPinia } from '@pinia/testing';
import { merge } from 'lodash-es';
import RunData from '@/components/RunData.vue';
import { SET_NODE_TYPE, STORES, VIEWS } from '@/constants';
import { SETTINGS_STORE_DEFAULT_STATE } from '@/__tests__/utils';
import { createTestWorkflowObject, defaultNodeDescriptions } from '@/__tests__/mocks';
import { createComponentRenderer } from '@/__tests__/render';
import { SETTINGS_STORE_DEFAULT_STATE } from '@/__tests__/utils';
import RunData from '@/components/RunData.vue';
import { SET_NODE_TYPE, STORES } from '@/constants';
import type { INodeUi, IRunDataDisplayMode, NodePanelType } from '@/Interface';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { setActivePinia } from 'pinia';
import { defaultNodeTypes } from '@/__tests__/mocks';
import { createTestingPinia } from '@pinia/testing';
import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/vue';
import type { INodeExecutionData } from 'n8n-workflow';
import { setActivePinia } from 'pinia';
import { useNodeTypesStore } from '../stores/nodeTypes.store';
vi.mock('vue-router', () => {
return {
useRouter: () => ({}),
useRoute: () => ({ meta: {} }),
RouterLink: vi.fn(),
};
});
const nodes = [
{
@ -112,9 +120,12 @@ describe('RunData', () => {
],
'binary',
);
expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
await waitFor(() => {
expect(getByTestId('ndv-view-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
});
});
it('should not render a view button for unknown content-type', async () => {
@ -132,9 +143,12 @@ describe('RunData', () => {
],
'binary',
);
expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
await waitFor(() => {
expect(queryByTestId('ndv-view-binary-data')).not.toBeInTheDocument();
expect(getByTestId('ndv-download-binary-data')).toBeInTheDocument();
expect(getByTestId('ndv-binary-data_0')).toBeInTheDocument();
});
});
it('should not render pin data button when there is no output data', async () => {
@ -201,10 +215,9 @@ describe('RunData', () => {
paneType: NodePanelType = 'output',
) => {
const pinia = createTestingPinia({
stubActions: false,
initialState: {
[STORES.SETTINGS]: {
settings: merge({}, SETTINGS_STORE_DEFAULT_STATE.settings),
},
[STORES.SETTINGS]: SETTINGS_STORE_DEFAULT_STATE,
[STORES.NDV]: {
output: {
displayMode,
@ -248,16 +261,17 @@ describe('RunData', () => {
},
},
},
[STORES.NODE_TYPES]: {
nodeTypes: defaultNodeTypes,
},
},
});
setActivePinia(pinia);
const workflowsStore = useWorkflowsStore();
const nodeTypesStore = useNodeTypesStore();
nodeTypesStore.setNodeTypes(defaultNodeDescriptions);
vi.mocked(workflowsStore).getNodeByName.mockReturnValue(nodes[0]);
if (pinnedData) {
vi.mocked(workflowsStore).pinDataByNodeName.mockReturnValue(pinnedData);
}
@ -267,31 +281,21 @@ describe('RunData', () => {
node: {
name: 'Test Node',
},
workflow: {
workflow: createTestWorkflowObject({
nodes,
},
},
data() {
return {
canPinData: true,
showData: true,
};
}),
},
global: {
stubs: {
RunDataPinButton: { template: '<button data-test-id="ndv-pin-data"></button>' },
},
mocks: {
$route: {
name: VIEWS.WORKFLOW,
},
},
},
})({
props: {
node: {
id: '1',
name: 'Test Node',
type: SET_NODE_TYPE,
position: [0, 0],
},
nodes: [{ name: 'Test Node', indicies: [], depth: 1 }],

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@
import { computed } from 'vue';
import { useI18n } from '@/composables/useI18n';
import type { usePinnedData } from '@/composables/usePinnedData';
import { N8nIconButton, N8nLink, N8nText, N8nTooltip } from 'n8n-design-system';
const locale = useI18n();
@ -27,7 +28,7 @@ const visible = computed(() =>
</script>
<template>
<n8n-tooltip placement="bottom-end" :visible="visible">
<N8nTooltip placement="bottom-end" :visible="visible">
<template #content>
<div v-if="props.tooltipContentsVisibility.binaryDataTooltipContent">
{{ locale.baseText('ndv.pinData.pin.binary') }}
@ -37,16 +38,16 @@ const visible = computed(() =>
</div>
<div v-else>
<strong>{{ locale.baseText('ndv.pinData.pin.title') }}</strong>
<n8n-text size="small" tag="p">
<N8nText size="small" tag="p">
{{ locale.baseText('ndv.pinData.pin.description') }}
<n8n-link :to="props.dataPinningDocsUrl" size="small">
<N8nLink :to="props.dataPinningDocsUrl" size="small">
{{ locale.baseText('ndv.pinData.pin.link') }}
</n8n-link>
</n8n-text>
</N8nLink>
</N8nText>
</div>
</template>
<n8n-icon-button
<N8nIconButton
:class="$style.pinDataButton"
type="tertiary"
:active="props.pinnedData.hasData.value"
@ -55,7 +56,7 @@ const visible = computed(() =>
data-test-id="ndv-pin-data"
@click="emit('togglePinData')"
/>
</n8n-tooltip>
</N8nTooltip>
</template>
<style lang="scss" module>

View file

@ -409,6 +409,7 @@ watch(
</template>
</i18n-t>
</n8n-text>
<n8n-text>{{ $locale.baseText('ndv.search.noMatchSchema.description') }}</n8n-text>
</div>
<div v-else :class="$style.schema" data-test-id="run-data-schema-node-schema">

View file

@ -31,7 +31,7 @@ const { debounce } = useDebounce();
const inputRef = ref<HTMLInputElement | null>(null);
const search = ref(props.modelValue ?? '');
const opened = ref(false);
const opened = ref(!!search.value);
const placeholder = computed(() => {
if (props.paneType === 'output') {
return locale.baseText('ndv.search.placeholder.output');

View file

@ -1,389 +1,387 @@
<script lang="ts">
import { defineComponent } from 'vue';
import type { PropType } from 'vue';
import { mapStores } from 'pinia';
import type { INodeUi, ITableData, NDVState } from '@/Interface';
import { shorten } from '@/utils/typesUtils';
import { getPairedItemId } from '@/utils/pairedItemUtils';
import type { GenericValue, IDataObject, INodeExecutionData } from 'n8n-workflow';
import Draggable from './Draggable.vue';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { useNDVStore } from '@/stores/ndv.store';
import MappingPill from './MappingPill.vue';
import { getMappedExpression } from '@/utils/mappingUtils';
<script setup lang="ts">
import { useExternalHooks } from '@/composables/useExternalHooks';
import type { INodeUi, IRunDataDisplayMode, ITableData } from '@/Interface';
import { useNDVStore } from '@/stores/ndv.store';
import { useWorkflowsStore } from '@/stores/workflows.store';
import { getMappedExpression } from '@/utils/mappingUtils';
import { getPairedItemId } from '@/utils/pairedItemUtils';
import { shorten } from '@/utils/typesUtils';
import type { GenericValue, IDataObject, INodeExecutionData } from 'n8n-workflow';
import { computed, onMounted, ref, watch } from 'vue';
import Draggable from './Draggable.vue';
import MappingPill from './MappingPill.vue';
import TextWithHighlights from './TextWithHighlights.vue';
import { useI18n } from '@/composables/useI18n';
import { useTelemetry } from '@/composables/useTelemetry';
import { N8nInfoTip, N8nTooltip, N8nTree } from 'n8n-design-system';
import { storeToRefs } from 'pinia';
const MAX_COLUMNS_LIMIT = 40;
type DraggableRef = InstanceType<typeof Draggable>;
export default defineComponent({
name: 'RunDataTable',
components: { Draggable, MappingPill, TextWithHighlights },
props: {
node: {
type: Object as PropType<INodeUi>,
required: true,
},
inputData: {
type: Array as PropType<INodeExecutionData[]>,
required: true,
},
mappingEnabled: {
type: Boolean,
},
distanceFromActive: {
type: Number,
required: true,
},
runIndex: {
type: Number,
},
outputIndex: {
type: Number,
},
totalRuns: {
type: Number,
},
pageOffset: {
type: Number,
required: true,
},
hasDefaultHoverState: {
type: Boolean,
},
search: {
type: String,
},
},
setup() {
const externalHooks = useExternalHooks();
return {
externalHooks,
};
},
data() {
return {
activeColumn: -1,
forceShowGrip: false,
draggedColumn: false,
draggingPath: null as null | string,
hoveringPath: null as null | string,
mappingHintVisible: false,
activeRow: null as number | null,
columnLimit: MAX_COLUMNS_LIMIT,
columnLimitExceeded: false,
};
},
mounted() {
if (this.tableData && this.tableData.columns && this.$refs.draggable) {
const tbody = (this.$refs.draggable as DraggableRef).$refs.wrapper as HTMLElement;
if (tbody) {
this.$emit('mounted', {
avgRowHeight: tbody.offsetHeight / this.tableData.data.length,
});
}
type Props = {
node: INodeUi;
inputData: INodeExecutionData[];
distanceFromActive: number;
pageOffset: number;
runIndex?: number;
outputIndex?: number;
totalRuns?: number;
mappingEnabled?: boolean;
hasDefaultHoverState?: boolean;
search?: string;
};
const props = withDefaults(defineProps<Props>(), {
runIndex: 0,
outputIndex: 0,
totalRuns: 0,
mappingEnabled: false,
hasDefaultHoverState: false,
search: '',
});
const emit = defineEmits<{
activeRowChanged: [row: number | null];
displayModeChange: [mode: IRunDataDisplayMode];
mounted: [data: { avgRowHeight: number }];
}>();
const externalHooks = useExternalHooks();
const activeColumn = ref(-1);
const forceShowGrip = ref(false);
const draggedColumn = ref(false);
const draggingPath = ref<string | null>(null);
const hoveringPath = ref<string | null>(null);
const activeRow = ref<number | null>(null);
const columnLimit = ref(MAX_COLUMNS_LIMIT);
const columnLimitExceeded = ref(false);
const draggableRef = ref<DraggableRef>();
const ndvStore = useNDVStore();
const workflowsStore = useWorkflowsStore();
const i18n = useI18n();
const telemetry = useTelemetry();
const {
hoveringItem,
focusedMappableInput,
highlightDraggables: highlight,
} = storeToRefs(ndvStore);
const pairedItemMappings = computed(() => workflowsStore.workflowExecutionPairedItemMappings);
const tableData = computed(() => convertToTable(props.inputData));
onMounted(() => {
if (tableData.value?.columns && draggableRef.value) {
const tbody = draggableRef.value.$refs.wrapper as HTMLElement;
if (tbody) {
emit('mounted', {
avgRowHeight: tbody.offsetHeight / tableData.value.data.length,
});
}
},
computed: {
...mapStores(useNDVStore, useWorkflowsStore),
hoveringItem(): NDVState['hoveringItem'] {
return this.ndvStore.hoveringItem;
},
pairedItemMappings(): { [itemId: string]: Set<string> } {
return this.workflowsStore.workflowExecutionPairedItemMappings;
},
tableData(): ITableData {
return this.convertToTable(this.inputData);
},
focusedMappableInput(): string {
return this.ndvStore.focusedMappableInput;
},
highlight(): boolean {
return this.ndvStore.highlightDraggables;
},
},
methods: {
shorten,
isHoveringRow(row: number): boolean {
if (row === this.activeRow) {
return true;
}
}
});
const itemIndex = this.pageOffset + row;
if (
itemIndex === 0 &&
!this.hoveringItem &&
this.hasDefaultHoverState &&
this.distanceFromActive === 1
) {
return true;
}
const itemNodeId = getPairedItemId(
this.node?.name ?? '',
this.runIndex || 0,
this.outputIndex || 0,
itemIndex,
);
if (!this.hoveringItem || !this.pairedItemMappings[itemNodeId]) {
return false;
}
function isHoveringRow(row: number): boolean {
if (row === activeRow.value) {
return true;
}
const hoveringItemId = getPairedItemId(
this.hoveringItem.nodeName,
this.hoveringItem.runIndex,
this.hoveringItem.outputIndex,
this.hoveringItem.itemIndex,
);
return this.pairedItemMappings[itemNodeId].has(hoveringItemId);
},
onMouseEnterCell(e: MouseEvent) {
const target = e.target;
if (target && this.mappingEnabled) {
const col = (target as HTMLElement).dataset.col;
if (col && !isNaN(parseInt(col, 10))) {
this.activeColumn = parseInt(col, 10);
}
const itemIndex = props.pageOffset + row;
if (
itemIndex === 0 &&
!hoveringItem.value &&
props.hasDefaultHoverState &&
props.distanceFromActive === 1
) {
return true;
}
const itemNodeId = getPairedItemId(
props.node?.name ?? '',
props.runIndex || 0,
props.outputIndex || 0,
itemIndex,
);
if (!hoveringItem.value || !pairedItemMappings.value[itemNodeId]) {
return false;
}
const hoveringItemId = getPairedItemId(
hoveringItem.value.nodeName,
hoveringItem.value.runIndex,
hoveringItem.value.outputIndex,
hoveringItem.value.itemIndex,
);
return pairedItemMappings.value[itemNodeId].has(hoveringItemId);
}
function onMouseEnterCell(e: MouseEvent) {
const target = e.target;
if (target && props.mappingEnabled) {
const col = (target as HTMLElement).dataset.col;
if (col && !isNaN(parseInt(col, 10))) {
activeColumn.value = parseInt(col, 10);
}
}
if (target) {
const row = (target as HTMLElement).dataset.row;
if (row && !isNaN(parseInt(row, 10))) {
activeRow.value = parseInt(row, 10);
emit('activeRowChanged', props.pageOffset + activeRow.value);
}
}
}
function onMouseLeaveCell() {
activeColumn.value = -1;
activeRow.value = null;
emit('activeRowChanged', null);
}
function onMouseEnterKey(path: Array<string | number>, colIndex: number) {
hoveringPath.value = getCellExpression(path, colIndex);
}
function onMouseLeaveKey() {
hoveringPath.value = null;
}
function isHovering(path: Array<string | number>, colIndex: number) {
const expr = getCellExpression(path, colIndex);
return hoveringPath.value === expr;
}
function getExpression(column: string) {
if (!props.node) {
return '';
}
return getMappedExpression({
nodeName: props.node.name,
distanceFromActive: props.distanceFromActive,
path: [column],
});
}
function getPathNameFromTarget(el?: HTMLElement) {
if (!el) {
return '';
}
return el.dataset.name;
}
function getCellPathName(path: Array<string | number>, colIndex: number) {
const lastKey = path[path.length - 1];
if (typeof lastKey === 'string') {
return lastKey;
}
if (path.length > 1) {
const prevKey = path[path.length - 2];
return `${prevKey}[${lastKey}]`;
}
const column = tableData.value.columns[colIndex];
return `${column}[${lastKey}]`;
}
function getCellExpression(path: Array<string | number>, colIndex: number) {
if (!props.node) {
return '';
}
const column = tableData.value.columns[colIndex];
return getMappedExpression({
nodeName: props.node.name,
distanceFromActive: props.distanceFromActive,
path: [column, ...path],
});
}
function isEmpty(value: unknown): boolean {
return (
value === '' ||
(Array.isArray(value) && value.length === 0) ||
(typeof value === 'object' && value !== null && Object.keys(value).length === 0) ||
value === null ||
value === undefined
);
}
function getValueToRender(value: unknown): string {
if (value === '') {
return i18n.baseText('runData.emptyString');
}
if (typeof value === 'string') {
return value;
}
if (Array.isArray(value) && value.length === 0) {
return i18n.baseText('runData.emptyArray');
}
if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
return i18n.baseText('runData.emptyObject');
}
if (value === null || value === undefined) {
return `[${value}]`;
}
if (value === true || value === false || typeof value === 'number') {
return value.toString();
}
return JSON.stringify(value);
}
function onDragStart() {
draggedColumn.value = true;
ndvStore.resetMappingTelemetry();
}
function onCellDragStart(el: HTMLElement) {
if (el?.dataset.value) {
draggingPath.value = el.dataset.value;
}
onDragStart();
}
function onCellDragEnd(el: HTMLElement) {
draggingPath.value = null;
onDragEnd(el.dataset.name ?? '', 'tree', el.dataset.depth ?? '0');
}
function isDraggingKey(path: Array<string | number>, colIndex: number) {
if (!draggingPath.value) {
return;
}
return draggingPath.value === getCellExpression(path, colIndex);
}
function onDragEnd(column: string, src: string, depth = '0') {
setTimeout(() => {
const mappingTelemetry = ndvStore.mappingTelemetry;
const telemetryPayload = {
src_node_type: props.node.type,
src_field_name: column,
src_nodes_back: props.distanceFromActive,
src_run_index: props.runIndex,
src_runs_total: props.totalRuns,
src_field_nest_level: parseInt(depth, 10),
src_view: 'table',
src_element: src,
success: false,
...mappingTelemetry,
};
void externalHooks.run('runDataTable.onDragEnd', telemetryPayload);
telemetry.track('User dragged data for mapping', telemetryPayload, {
withPostHog: true,
});
}, 1000); // ensure dest data gets set if drop
}
function isSimple(data: GenericValue): data is string | number | boolean | null | undefined {
return (
typeof data !== 'object' ||
data === null ||
(Array.isArray(data) && data.length === 0) ||
(typeof data === 'object' && Object.keys(data).length === 0)
);
}
function isObject(data: GenericValue): data is Record<string, unknown> {
return !isSimple(data);
}
function hasJsonInColumn(colIndex: number): boolean {
return tableData.value.hasJson[tableData.value.columns[colIndex]];
}
function convertToTable(inputData: INodeExecutionData[]): ITableData {
const resultTableData: GenericValue[][] = [];
const tableColumns: string[] = [];
let leftEntryColumns: string[], entryRows: GenericValue[];
// Go over all entries
let entry: IDataObject;
const hasJson: { [key: string]: boolean } = {};
inputData.forEach((data) => {
if (!data.hasOwnProperty('json')) {
return;
}
entry = data.json;
// Go over all keys of entry
entryRows = [];
const entryColumns = Object.keys(entry || {});
if (entryColumns.length > MAX_COLUMNS_LIMIT) {
columnLimitExceeded.value = true;
leftEntryColumns = entryColumns.slice(0, MAX_COLUMNS_LIMIT);
} else {
leftEntryColumns = entryColumns;
}
// Go over all the already existing column-keys
tableColumns.forEach((key) => {
if (entry.hasOwnProperty(key)) {
// Entry does have key so add its value
entryRows.push(entry[key]);
// Remove key so that we know that it got added
leftEntryColumns.splice(leftEntryColumns.indexOf(key), 1);
hasJson[key] =
hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] ?? {}).length > 0) ||
false;
} else {
// Entry does not have key so add undefined
entryRows.push(undefined);
}
});
if (target) {
const row = (target as HTMLElement).dataset.row;
if (row && !isNaN(parseInt(row, 10))) {
this.activeRow = parseInt(row, 10);
this.$emit('activeRowChanged', this.pageOffset + this.activeRow);
}
}
},
onMouseLeaveCell() {
this.activeColumn = -1;
this.activeRow = null;
this.$emit('activeRowChanged', null);
},
onMouseEnterKey(path: string[], colIndex: number) {
this.hoveringPath = this.getCellExpression(path, colIndex);
},
onMouseLeaveKey() {
this.hoveringPath = null;
},
isHovering(path: string[], colIndex: number) {
const expr = this.getCellExpression(path, colIndex);
// Go over all the columns the entry has but did not exist yet
leftEntryColumns.forEach((key) => {
// Add the key for all runs in the future
tableColumns.push(key);
// Add the value
entryRows.push(entry[key]);
hasJson[key] =
hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] ?? {}).length > 0) ||
false;
});
return this.hoveringPath === expr;
},
getExpression(column: string) {
if (!this.node) {
return '';
}
// Add the data of the entry
resultTableData.push(entryRows);
});
return getMappedExpression({
nodeName: this.node.name,
distanceFromActive: this.distanceFromActive,
path: [column],
});
},
getPathNameFromTarget(el?: HTMLElement) {
if (!el) {
return '';
}
return el.dataset.name;
},
getCellPathName(path: Array<string | number>, colIndex: number) {
const lastKey = path[path.length - 1];
if (typeof lastKey === 'string') {
return lastKey;
}
if (path.length > 1) {
const prevKey = path[path.length - 2];
return `${prevKey}[${lastKey}]`;
}
const column = this.tableData.columns[colIndex];
return `${column}[${lastKey}]`;
},
getCellExpression(path: Array<string | number>, colIndex: number) {
if (!this.node) {
return '';
}
const column = this.tableData.columns[colIndex];
return getMappedExpression({
nodeName: this.node.name,
distanceFromActive: this.distanceFromActive,
path: [column, ...path],
});
},
isEmpty(value: unknown): boolean {
return (
value === '' ||
(Array.isArray(value) && value.length === 0) ||
(typeof value === 'object' && value !== null && Object.keys(value).length === 0) ||
value === null ||
value === undefined
);
},
getValueToRender(value: unknown): string {
if (value === '') {
return this.$locale.baseText('runData.emptyString');
}
if (typeof value === 'string') {
return value;
}
if (Array.isArray(value) && value.length === 0) {
return this.$locale.baseText('runData.emptyArray');
}
if (typeof value === 'object' && value !== null && Object.keys(value).length === 0) {
return this.$locale.baseText('runData.emptyObject');
}
if (value === null || value === undefined) {
return `[${value}]`;
}
if (value === true || value === false || typeof value === 'number') {
return value.toString();
}
return JSON.stringify(value);
},
onDragStart() {
this.draggedColumn = true;
this.ndvStore.resetMappingTelemetry();
},
onCellDragStart(el: HTMLElement) {
if (el?.dataset.value) {
this.draggingPath = el.dataset.value;
}
// Make sure that all entry-rows have the same length
resultTableData.forEach((rows) => {
if (tableColumns.length > rows.length) {
// Has fewer entries so add the missing ones
rows.push(...new Array(tableColumns.length - rows.length));
}
});
this.onDragStart();
return {
hasJson,
columns: tableColumns,
data: resultTableData,
};
}
function switchToJsonView() {
emit('displayModeChange', 'json');
}
watch(focusedMappableInput, (curr) => {
setTimeout(
() => {
forceShowGrip.value = !!focusedMappableInput.value;
},
onCellDragEnd(el: HTMLElement) {
this.draggingPath = null;
this.onDragEnd(el.dataset.name || '', 'tree', el.dataset.depth || '0');
},
isDraggingKey(path: Array<string | number>, colIndex: number) {
if (!this.draggingPath) {
return;
}
return this.draggingPath === this.getCellExpression(path, colIndex);
},
onDragEnd(column: string, src: string, depth = '0') {
setTimeout(() => {
const mappingTelemetry = this.ndvStore.mappingTelemetry;
const telemetryPayload = {
src_node_type: this.node.type,
src_field_name: column,
src_nodes_back: this.distanceFromActive,
src_run_index: this.runIndex,
src_runs_total: this.totalRuns,
src_field_nest_level: parseInt(depth, 10),
src_view: 'table',
src_element: src,
success: false,
...mappingTelemetry,
};
void this.externalHooks.run('runDataTable.onDragEnd', telemetryPayload);
this.$telemetry.track('User dragged data for mapping', telemetryPayload, {
withPostHog: true,
});
}, 1000); // ensure dest data gets set if drop
},
isSimple(data: unknown): boolean {
return (
typeof data !== 'object' ||
data === null ||
(Array.isArray(data) && data.length === 0) ||
(typeof data === 'object' && Object.keys(data).length === 0)
);
},
hasJsonInColumn(colIndex: number): boolean {
return this.tableData.hasJson[this.tableData.columns[colIndex]];
},
convertToTable(inputData: INodeExecutionData[]): ITableData {
const tableData: GenericValue[][] = [];
const tableColumns: string[] = [];
let leftEntryColumns: string[], entryRows: GenericValue[];
// Go over all entries
let entry: IDataObject;
const hasJson: { [key: string]: boolean } = {};
inputData.forEach((data) => {
if (!data.hasOwnProperty('json')) {
return;
}
entry = data.json;
// Go over all keys of entry
entryRows = [];
const entryColumns = Object.keys(entry || {});
if (entryColumns.length > MAX_COLUMNS_LIMIT) {
this.columnLimitExceeded = true;
leftEntryColumns = entryColumns.slice(0, MAX_COLUMNS_LIMIT);
} else {
leftEntryColumns = entryColumns;
}
// Go over all the already existing column-keys
tableColumns.forEach((key) => {
if (entry.hasOwnProperty(key)) {
// Entry does have key so add its value
entryRows.push(entry[key]);
// Remove key so that we know that it got added
leftEntryColumns.splice(leftEntryColumns.indexOf(key), 1);
hasJson[key] =
hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] || {}).length > 0) ||
false;
} else {
// Entry does not have key so add undefined
entryRows.push(undefined);
}
});
// Go over all the columns the entry has but did not exist yet
leftEntryColumns.forEach((key) => {
// Add the key for all runs in the future
tableColumns.push(key);
// Add the value
entryRows.push(entry[key]);
hasJson[key] =
hasJson[key] ||
(typeof entry[key] === 'object' && Object.keys(entry[key] || {}).length > 0) ||
false;
});
// Add the data of the entry
tableData.push(entryRows);
});
// Make sure that all entry-rows have the same length
tableData.forEach((entryRows) => {
if (tableColumns.length > entryRows.length) {
// Has fewer entries so add the missing ones
entryRows.push(...new Array(tableColumns.length - entryRows.length));
}
});
return {
hasJson,
columns: tableColumns,
data: tableData,
};
},
switchToJsonView() {
this.$emit('displayModeChange', 'json');
},
},
watch: {
focusedMappableInput(curr: boolean) {
setTimeout(
() => {
this.forceShowGrip = !!this.focusedMappableInput;
},
curr ? 300 : 150,
);
},
},
curr ? 300 : 150,
);
});
</script>
@ -408,7 +406,7 @@ export default defineComponent({
@mouseenter="onMouseEnterCell"
@mouseleave="onMouseLeaveCell"
>
<n8n-info-tip>{{ $locale.baseText('runData.emptyItemHint') }}</n8n-info-tip>
<N8nInfoTip>{{ i18n.baseText('runData.emptyItemHint') }}</N8nInfoTip>
</td>
<td :class="$style.tableRightMargin"></td>
</tr>
@ -418,11 +416,11 @@ export default defineComponent({
<thead>
<tr>
<th v-for="(column, i) in tableData.columns || []" :key="column">
<n8n-tooltip placement="bottom-start" :disabled="!mappingEnabled" :show-after="1000">
<N8nTooltip placement="bottom-start" :disabled="!mappingEnabled" :show-after="1000">
<template #content>
<div>
<img src="/static/data-mapping-gif.gif" />
{{ $locale.baseText('dataMapping.dragColumnToFieldHint') }}
{{ i18n.baseText('dataMapping.dragColumnToFieldHint') }}
</div>
</template>
<Draggable
@ -455,17 +453,17 @@ export default defineComponent({
</div>
</template>
</Draggable>
</n8n-tooltip>
</N8nTooltip>
</th>
<th v-if="columnLimitExceeded" :class="$style.header">
<n8n-tooltip placement="bottom-end">
<N8nTooltip placement="bottom-end">
<template #content>
<div>
<i18n-t tag="span" keypath="dataMapping.tableView.tableColumnsExceeded.tooltip">
<template #columnLimit>{{ columnLimit }}</template>
<template #link>
<a @click="switchToJsonView">{{
$locale.baseText('dataMapping.tableView.tableColumnsExceeded.tooltip.link')
i18n.baseText('dataMapping.tableView.tableColumnsExceeded.tooltip.link')
}}</a>
</template>
</i18n-t>
@ -476,15 +474,15 @@ export default defineComponent({
:class="$style['warningTooltip']"
icon="exclamation-triangle"
></font-awesome-icon>
{{ $locale.baseText('dataMapping.tableView.tableColumnsExceeded') }}
{{ i18n.baseText('dataMapping.tableView.tableColumnsExceeded') }}
</span>
</n8n-tooltip>
</N8nTooltip>
</th>
<th :class="$style.tableRightMargin"></th>
</tr>
</thead>
<Draggable
ref="draggable"
ref="draggableRef"
tag="tbody"
type="mapping"
target-data-key="mappable"
@ -519,7 +517,7 @@ export default defineComponent({
:search="search"
:class="{ [$style.value]: true, [$style.empty]: isEmpty(data) }"
/>
<n8n-tree v-else :node-class="$style.nodeClass" :value="data">
<N8nTree v-else-if="isObject(data)" :node-class="$style.nodeClass" :value="data">
<template #label="{ label, path }">
<span
:class="{
@ -534,9 +532,10 @@ export default defineComponent({
:data-depth="path.length"
@mouseenter="() => onMouseEnterKey(path, index2)"
@mouseleave="onMouseLeaveKey"
>{{ label || $locale.baseText('runData.unnamedField') }}</span
>{{ label || i18n.baseText('runData.unnamedField') }}</span
>
</template>
<template #value="{ value }">
<TextWithHighlights
:content="getValueToRender(value)"
@ -544,7 +543,7 @@ export default defineComponent({
:class="{ [$style.nestedValue]: true, [$style.empty]: isEmpty(value) }"
/>
</template>
</n8n-tree>
</N8nTree>
</td>
<td v-if="columnLimitExceeded"></td>
<td :class="$style.tableRightMargin"></td>

View file

@ -1,6 +1,5 @@
<script lang="ts">
import { defineComponent } from 'vue';
import { mapStores } from 'pinia';
<script setup lang="ts">
import { computed, ref } from 'vue';
import {
CHAT_TRIGGER_NODE_TYPE,
VIEWS,
@ -22,336 +21,348 @@ import { createEventBus } from 'n8n-design-system/utils';
import { useRouter } from 'vue-router';
import { useWorkflowHelpers } from '@/composables/useWorkflowHelpers';
import { isTriggerPanelObject } from '@/utils/typeGuards';
import { useI18n } from '@/composables/useI18n';
import { useTelemetry } from '@/composables/useTelemetry';
export default defineComponent({
name: 'TriggerPanel',
components: {
NodeExecuteButton,
CopyInput,
NodeIcon,
const props = withDefaults(
defineProps<{
nodeName: string;
pushRef: string;
}>(),
{
pushRef: '',
},
props: {
nodeName: {
type: String,
required: true,
},
pushRef: {
type: String,
default: '',
},
},
emits: { activate: null, execute: null },
setup() {
const router = useRouter();
const workflowHelpers = useWorkflowHelpers({ router });
);
return {
workflowHelpers,
};
},
data: () => {
return {
executionsHelpEventBus: createEventBus(),
};
},
computed: {
...mapStores(useNodeTypesStore, useNDVStore, useUIStore, useWorkflowsStore),
node(): INodeUi | null {
return this.workflowsStore.getNodeByName(this.nodeName);
},
nodeType(): INodeTypeDescription | null {
if (this.node) {
return this.nodeTypesStore.getNodeType(this.node.type, this.node.typeVersion);
}
const emit = defineEmits<{
activate: [];
execute: [];
}>();
return null;
},
triggerPanel() {
const panel = this.nodeType?.triggerPanel;
if (isTriggerPanelObject(panel)) {
return panel;
}
return undefined;
},
hideContent(): boolean {
const hideContent = this.triggerPanel?.hideContent;
if (typeof hideContent === 'boolean') {
return hideContent;
}
const nodesTypeStore = useNodeTypesStore();
const uiStore = useUIStore();
const workflowsStore = useWorkflowsStore();
const ndvStore = useNDVStore();
if (this.node) {
const hideContentValue = this.workflowHelpers
.getCurrentWorkflow()
.expression.getSimpleParameterValue(this.node, hideContent, 'internal', {});
const router = useRouter();
const workflowHelpers = useWorkflowHelpers({ router });
const i18n = useI18n();
const telemetry = useTelemetry();
if (typeof hideContentValue === 'boolean') {
return hideContentValue;
}
}
const executionsHelpEventBus = createEventBus();
return false;
},
hasIssues(): boolean {
return Boolean(
this.node?.issues && (this.node.issues.parameters ?? this.node.issues.credentials),
);
},
serviceName(): string {
if (this.nodeType) {
return getTriggerNodeServiceName(this.nodeType);
}
const help = ref<HTMLElement | null>(null);
return '';
},
displayChatButton(): boolean {
return Boolean(
this.node &&
this.node.type === CHAT_TRIGGER_NODE_TYPE &&
this.node.parameters.mode !== 'webhook',
);
},
isWebhookNode(): boolean {
return Boolean(this.node && this.node.type === WEBHOOK_NODE_TYPE);
},
webhookHttpMethod(): string | undefined {
if (!this.node || !this.nodeType?.webhooks?.length) {
return undefined;
}
const node = computed<INodeUi | null>(() => workflowsStore.getNodeByName(props.nodeName));
const httpMethod = this.workflowHelpers.getWebhookExpressionValue(
this.nodeType.webhooks[0],
'httpMethod',
false,
);
const nodeType = computed<INodeTypeDescription | null>(() => {
if (node.value) {
return nodesTypeStore.getNodeType(node.value.type, node.value.typeVersion);
}
if (Array.isArray(httpMethod)) {
return httpMethod.join(', ');
}
return httpMethod;
},
webhookTestUrl(): string | undefined {
if (!this.node || !this.nodeType?.webhooks?.length) {
return undefined;
}
return this.workflowHelpers.getWebhookUrl(this.nodeType.webhooks[0], this.node, 'test');
},
isWebhookBasedNode(): boolean {
return Boolean(this.nodeType?.webhooks?.length);
},
isPollingNode(): boolean {
return Boolean(this.nodeType?.polling);
},
isListeningForEvents(): boolean {
const waitingOnWebhook = this.workflowsStore.executionWaitingForWebhook;
const executedNode = this.workflowsStore.executedNode;
return (
!!this.node &&
!this.node.disabled &&
this.isWebhookBasedNode &&
waitingOnWebhook &&
(!executedNode || executedNode === this.nodeName)
);
},
workflowRunning(): boolean {
return this.uiStore.isActionActive['workflowRunning'];
},
isActivelyPolling(): boolean {
const triggeredNode = this.workflowsStore.executedNode;
return this.workflowRunning && this.isPollingNode && this.nodeName === triggeredNode;
},
isWorkflowActive(): boolean {
return this.workflowsStore.isWorkflowActive;
},
listeningTitle(): string {
return this.nodeType?.name === FORM_TRIGGER_NODE_TYPE
? this.$locale.baseText('ndv.trigger.webhookNode.formTrigger.listening')
: this.$locale.baseText('ndv.trigger.webhookNode.listening');
},
listeningHint(): string {
switch (this.nodeType?.name) {
case CHAT_TRIGGER_NODE_TYPE:
return this.$locale.baseText('ndv.trigger.webhookBasedNode.chatTrigger.serviceHint');
case FORM_TRIGGER_NODE_TYPE:
return this.$locale.baseText('ndv.trigger.webhookBasedNode.formTrigger.serviceHint');
default:
return this.$locale.baseText('ndv.trigger.webhookBasedNode.serviceHint', {
interpolate: { service: this.serviceName },
});
}
},
header(): string {
const serviceName = this.nodeType ? getTriggerNodeServiceName(this.nodeType) : '';
if (this.isActivelyPolling) {
return this.$locale.baseText('ndv.trigger.pollingNode.fetchingEvent');
}
if (this.triggerPanel?.header) {
return this.triggerPanel.header;
}
if (this.isWebhookBasedNode) {
return this.$locale.baseText('ndv.trigger.webhookBasedNode.action', {
interpolate: { name: serviceName },
});
}
return '';
},
subheader(): string {
const serviceName = this.nodeType ? getTriggerNodeServiceName(this.nodeType) : '';
if (this.isActivelyPolling) {
return this.$locale.baseText('ndv.trigger.pollingNode.fetchingHint', {
interpolate: { name: serviceName },
});
}
return '';
},
executionsHelp(): string {
if (this.triggerPanel?.executionsHelp) {
if (typeof this.triggerPanel.executionsHelp === 'string') {
return this.triggerPanel.executionsHelp;
}
if (!this.isWorkflowActive && this.triggerPanel.executionsHelp.inactive) {
return this.triggerPanel.executionsHelp.inactive;
}
if (this.isWorkflowActive && this.triggerPanel.executionsHelp.active) {
return this.triggerPanel.executionsHelp.active;
}
}
if (this.isWebhookBasedNode) {
if (this.isWorkflowActive) {
return this.$locale.baseText('ndv.trigger.webhookBasedNode.executionsHelp.active', {
interpolate: { service: this.serviceName },
});
} else {
return this.$locale.baseText('ndv.trigger.webhookBasedNode.executionsHelp.inactive', {
interpolate: { service: this.serviceName },
});
}
}
if (this.isPollingNode) {
if (this.isWorkflowActive) {
return this.$locale.baseText('ndv.trigger.pollingNode.executionsHelp.active', {
interpolate: { service: this.serviceName },
});
} else {
return this.$locale.baseText('ndv.trigger.pollingNode.executionsHelp.inactive', {
interpolate: { service: this.serviceName },
});
}
}
return '';
},
activationHint(): string {
if (this.isActivelyPolling || !this.triggerPanel) {
return '';
}
if (this.triggerPanel.activationHint) {
if (typeof this.triggerPanel.activationHint === 'string') {
return this.triggerPanel.activationHint;
}
if (
!this.isWorkflowActive &&
typeof this.triggerPanel.activationHint.inactive === 'string'
) {
return this.triggerPanel.activationHint.inactive;
}
if (this.isWorkflowActive && typeof this.triggerPanel.activationHint.active === 'string') {
return this.triggerPanel.activationHint.active;
}
}
if (this.isWebhookBasedNode) {
if (this.isWorkflowActive) {
return this.$locale.baseText('ndv.trigger.webhookBasedNode.activationHint.active', {
interpolate: { service: this.serviceName },
});
} else {
return this.$locale.baseText('ndv.trigger.webhookBasedNode.activationHint.inactive', {
interpolate: { service: this.serviceName },
});
}
}
if (this.isPollingNode) {
if (this.isWorkflowActive) {
return this.$locale.baseText('ndv.trigger.pollingNode.activationHint.active', {
interpolate: { service: this.serviceName },
});
} else {
return this.$locale.baseText('ndv.trigger.pollingNode.activationHint.inactive', {
interpolate: { service: this.serviceName },
});
}
}
return '';
},
},
methods: {
expandExecutionHelp() {
if (this.$refs.help) {
this.executionsHelpEventBus.emit('expand');
}
},
openWebhookUrl() {
this.$telemetry.track('User clicked ndv link', {
workflow_id: this.workflowsStore.workflowId,
push_ref: this.pushRef,
pane: 'input',
type: 'open-chat',
});
window.open(this.webhookTestUrl, '_blank', 'noreferrer');
},
onLinkClick(e: MouseEvent) {
if (!e.target) {
return;
}
const target = e.target as HTMLElement;
if (target.localName !== 'a') return;
if (target.dataset?.key) {
e.stopPropagation();
e.preventDefault();
if (target.dataset.key === 'activate') {
this.$emit('activate');
} else if (target.dataset.key === 'executions') {
this.$telemetry.track('User clicked ndv link', {
workflow_id: this.workflowsStore.workflowId,
push_ref: this.pushRef,
pane: 'input',
type: 'open-executions-log',
});
this.ndvStore.activeNodeName = null;
void this.$router.push({
name: VIEWS.EXECUTIONS,
});
} else if (target.dataset.key === 'settings') {
this.uiStore.openModal(WORKFLOW_SETTINGS_MODAL_KEY);
}
}
},
onTestLinkCopied() {
this.$telemetry.track('User copied webhook URL', {
pane: 'inputs',
type: 'test url',
});
},
onNodeExecute() {
this.$emit('execute');
},
},
return null;
});
const triggerPanel = computed(() => {
const panel = nodeType.value?.triggerPanel;
if (isTriggerPanelObject(panel)) {
return panel;
}
return undefined;
});
const hideContent = computed(() => {
const hideContent = triggerPanel.value?.hideContent;
if (typeof hideContent === 'boolean') {
return hideContent;
}
if (node.value) {
const hideContentValue = workflowHelpers
.getCurrentWorkflow()
.expression.getSimpleParameterValue(node.value, hideContent, 'internal', {});
if (typeof hideContentValue === 'boolean') {
return hideContentValue;
}
}
return false;
});
const hasIssues = computed(() => {
return Boolean(
node.value?.issues && (node.value.issues.parameters ?? node.value.issues.credentials),
);
});
const serviceName = computed(() => {
if (nodeType.value) {
return getTriggerNodeServiceName(nodeType.value);
}
return '';
});
const displayChatButton = computed(() => {
return Boolean(
node.value &&
node.value.type === CHAT_TRIGGER_NODE_TYPE &&
node.value.parameters.mode !== 'webhook',
);
});
const isWebhookNode = computed(() => {
return Boolean(node.value && node.value.type === WEBHOOK_NODE_TYPE);
});
const webhookHttpMethod = computed(() => {
if (!node.value || !nodeType.value?.webhooks?.length) {
return undefined;
}
const httpMethod = workflowHelpers.getWebhookExpressionValue(
nodeType.value.webhooks[0],
'httpMethod',
false,
);
if (Array.isArray(httpMethod)) {
return httpMethod.join(', ');
}
return httpMethod;
});
const webhookTestUrl = computed(() => {
if (!node.value || !nodeType.value?.webhooks?.length) {
return undefined;
}
return workflowHelpers.getWebhookUrl(nodeType.value.webhooks[0], node.value, 'test');
});
const isWebhookBasedNode = computed(() => {
return Boolean(nodeType.value?.webhooks?.length);
});
const isPollingNode = computed(() => {
return Boolean(nodeType.value?.polling);
});
const isListeningForEvents = computed(() => {
const waitingOnWebhook = workflowsStore.executionWaitingForWebhook;
const executedNode = workflowsStore.executedNode;
return (
!!node.value &&
!node.value.disabled &&
isWebhookBasedNode.value &&
waitingOnWebhook &&
(!executedNode || executedNode === props.nodeName)
);
});
const workflowRunning = computed(() => {
return uiStore.isActionActive['workflowRunning'];
});
const isActivelyPolling = computed(() => {
const triggeredNode = workflowsStore.executedNode;
return workflowRunning.value && isPollingNode.value && props.nodeName === triggeredNode;
});
const isWorkflowActive = computed(() => {
return workflowsStore.isWorkflowActive;
});
const listeningTitle = computed(() => {
return nodeType.value?.name === FORM_TRIGGER_NODE_TYPE
? i18n.baseText('ndv.trigger.webhookNode.formTrigger.listening')
: i18n.baseText('ndv.trigger.webhookNode.listening');
});
const listeningHint = computed(() => {
switch (nodeType.value?.name) {
case CHAT_TRIGGER_NODE_TYPE:
return i18n.baseText('ndv.trigger.webhookBasedNode.chatTrigger.serviceHint');
case FORM_TRIGGER_NODE_TYPE:
return i18n.baseText('ndv.trigger.webhookBasedNode.formTrigger.serviceHint');
default:
return i18n.baseText('ndv.trigger.webhookBasedNode.serviceHint', {
interpolate: { service: serviceName.value },
});
}
});
const header = computed(() => {
if (isActivelyPolling.value) {
return i18n.baseText('ndv.trigger.pollingNode.fetchingEvent');
}
if (triggerPanel.value?.header) {
return triggerPanel.value.header;
}
if (isWebhookBasedNode.value) {
return i18n.baseText('ndv.trigger.webhookBasedNode.action', {
interpolate: { name: serviceName.value },
});
}
return '';
});
const subheader = computed(() => {
if (isActivelyPolling.value) {
return i18n.baseText('ndv.trigger.pollingNode.fetchingHint', {
interpolate: { name: serviceName.value },
});
}
return '';
});
const executionsHelp = computed(() => {
if (triggerPanel.value?.executionsHelp) {
if (typeof triggerPanel.value.executionsHelp === 'string') {
return triggerPanel.value.executionsHelp;
}
if (!isWorkflowActive.value && triggerPanel.value.executionsHelp.inactive) {
return triggerPanel.value.executionsHelp.inactive;
}
if (isWorkflowActive.value && triggerPanel.value.executionsHelp.active) {
return triggerPanel.value.executionsHelp.active;
}
}
if (isWebhookBasedNode.value) {
if (isWorkflowActive.value) {
return i18n.baseText('ndv.trigger.webhookBasedNode.executionsHelp.active', {
interpolate: { service: serviceName.value },
});
} else {
return i18n.baseText('ndv.trigger.webhookBasedNode.executionsHelp.inactive', {
interpolate: { service: serviceName.value },
});
}
}
if (isPollingNode.value) {
if (isWorkflowActive.value) {
return i18n.baseText('ndv.trigger.pollingNode.executionsHelp.active', {
interpolate: { service: serviceName.value },
});
} else {
return i18n.baseText('ndv.trigger.pollingNode.executionsHelp.inactive', {
interpolate: { service: serviceName.value },
});
}
}
return '';
});
const activationHint = computed(() => {
if (isActivelyPolling.value || !triggerPanel.value) {
return '';
}
if (triggerPanel.value.activationHint) {
if (typeof triggerPanel.value.activationHint === 'string') {
return triggerPanel.value.activationHint;
}
if (!isWorkflowActive.value && typeof triggerPanel.value.activationHint.inactive === 'string') {
return triggerPanel.value.activationHint.inactive;
}
if (isWorkflowActive.value && typeof triggerPanel.value.activationHint.active === 'string') {
return triggerPanel.value.activationHint.active;
}
}
if (isWebhookBasedNode.value) {
if (isWorkflowActive.value) {
return i18n.baseText('ndv.trigger.webhookBasedNode.activationHint.active', {
interpolate: { service: serviceName.value },
});
} else {
return i18n.baseText('ndv.trigger.webhookBasedNode.activationHint.inactive', {
interpolate: { service: serviceName.value },
});
}
}
if (isPollingNode.value) {
if (isWorkflowActive.value) {
return i18n.baseText('ndv.trigger.pollingNode.activationHint.active', {
interpolate: { service: serviceName.value },
});
} else {
return i18n.baseText('ndv.trigger.pollingNode.activationHint.inactive', {
interpolate: { service: serviceName.value },
});
}
}
return '';
});
const expandExecutionHelp = () => {
if (help.value) {
executionsHelpEventBus.emit('expand');
}
};
const openWebhookUrl = () => {
telemetry.track('User clicked ndv link', {
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input',
type: 'open-chat',
});
window.open(webhookTestUrl.value, '_blank', 'noreferrer');
};
const onLinkClick = (e: MouseEvent) => {
if (!e.target) {
return;
}
const target = e.target as HTMLElement;
if (target.localName !== 'a') return;
if (target.dataset?.key) {
e.stopPropagation();
e.preventDefault();
if (target.dataset.key === 'activate') {
emit('activate');
} else if (target.dataset.key === 'executions') {
telemetry.track('User clicked ndv link', {
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: 'input',
type: 'open-executions-log',
});
ndvStore.activeNodeName = null;
void router.push({
name: VIEWS.EXECUTIONS,
});
} else if (target.dataset.key === 'settings') {
uiStore.openModal(WORKFLOW_SETTINGS_MODAL_KEY);
}
}
};
const onTestLinkCopied = () => {
telemetry.track('User copied webhook URL', {
pane: 'inputs',
type: 'test url',
});
};
const onNodeExecute = () => {
emit('execute');
};
</script>
<template>
@ -364,12 +375,12 @@ export default defineComponent({
</n8n-pulse>
<div v-if="isWebhookNode">
<n8n-text tag="div" size="large" color="text-dark" class="mb-2xs" bold>{{
$locale.baseText('ndv.trigger.webhookNode.listening')
i18n.baseText('ndv.trigger.webhookNode.listening')
}}</n8n-text>
<div :class="[$style.shake, 'mb-xs']">
<n8n-text>
{{
$locale.baseText('ndv.trigger.webhookNode.requestHint', {
i18n.baseText('ndv.trigger.webhookNode.requestHint', {
interpolate: { type: webhookHttpMethod ?? '' },
})
}}
@ -377,11 +388,11 @@ export default defineComponent({
</div>
<CopyInput
:value="webhookTestUrl"
:toast-title="$locale.baseText('ndv.trigger.copiedTestUrl')"
:toast-title="i18n.baseText('ndv.trigger.copiedTestUrl')"
class="mb-2xl"
size="medium"
:collapse="true"
:copy-button-text="$locale.baseText('generic.clickToCopy')"
:copy-button-text="i18n.baseText('generic.clickToCopy')"
@copy="onTestLinkCopied"
></CopyInput>
<NodeExecuteButton
@ -403,7 +414,7 @@ export default defineComponent({
</div>
<div v-if="displayChatButton">
<n8n-button class="mb-xl" @click="openWebhookUrl()">
{{ $locale.baseText('ndv.trigger.chatTrigger.openChat') }}
{{ i18n.baseText('ndv.trigger.chatTrigger.openChat') }}
</n8n-button>
</div>
@ -447,13 +458,13 @@ export default defineComponent({
v-if="activationHint && executionsHelp"
size="small"
@click="expandExecutionHelp"
>{{ $locale.baseText('ndv.trigger.moreInfo') }}</n8n-link
>{{ i18n.baseText('ndv.trigger.moreInfo') }}</n8n-link
>
<n8n-info-accordion
v-if="executionsHelp"
ref="help"
:class="$style.accordion"
:title="$locale.baseText('ndv.trigger.executionsHint.question')"
:title="i18n.baseText('ndv.trigger.executionsHint.question')"
:description="executionsHelp"
:event-bus="executionsHelpEventBus"
@click:body="onLinkClick"

View file

@ -1,6 +1,5 @@
<script lang="ts">
import { defineComponent } from 'vue';
import { mapStores } from 'pinia';
<script setup lang="ts">
import { computed, watch, onMounted, ref } from 'vue';
import { createEventBus } from 'n8n-design-system/utils';
import Modal from './Modal.vue';
@ -8,10 +7,8 @@ import {
EnterpriseEditionFeature,
MODAL_CONFIRM,
PLACEHOLDER_EMPTY_WORKFLOW_ID,
VIEWS,
WORKFLOW_SHARE_MODAL_KEY,
} from '@/constants';
import type { IUser, IWorkflowDb } from '@/Interface';
import { getResourcePermissions } from '@/permissions';
import { useMessage } from '@/composables/useMessage';
import { useToast } from '@/composables/useToast';
@ -23,239 +20,208 @@ import { useWorkflowsStore } from '@/stores/workflows.store';
import { useWorkflowsEEStore } from '@/stores/workflows.ee.store';
import type { ITelemetryTrackProperties } from 'n8n-workflow';
import type { BaseTextKey } from '@/plugins/i18n';
import { isNavigationFailure } from 'vue-router';
import ProjectSharing from '@/components/Projects/ProjectSharing.vue';
import { useProjectsStore } from '@/stores/projects.store';
import type { ProjectListItem, ProjectSharingData, Project } from '@/types/projects.types';
import type { ProjectSharingData, Project } from '@/types/projects.types';
import { ProjectTypes } from '@/types/projects.types';
import { useRolesStore } from '@/stores/roles.store';
import type { RoleMap } from '@/types/roles.types';
import { usePageRedirectionHelper } from '@/composables/usePageRedirectionHelper';
import { useI18n } from '@/composables/useI18n';
import { telemetry } from '@/plugins/telemetry';
export default defineComponent({
name: 'WorkflowShareModal',
components: {
Modal,
ProjectSharing,
},
props: {
data: {
type: Object,
default: () => ({}),
},
},
setup() {
return {
...useToast(),
...useMessage(),
...usePageRedirectionHelper(),
};
},
data() {
const workflowsStore = useWorkflowsStore();
const workflow =
this.data.id === PLACEHOLDER_EMPTY_WORKFLOW_ID
? workflowsStore.workflow
: workflowsStore.workflowsById[this.data.id];
const props = defineProps<{
data: {
id: string;
};
}>();
return {
WORKFLOW_SHARE_MODAL_KEY,
loading: true,
isDirty: false,
modalBus: createEventBus(),
sharedWithProjects: [...(workflow.sharedWithProjects || [])] as ProjectSharingData[],
EnterpriseEditionFeature,
teamProject: null as Project | null,
};
},
computed: {
...mapStores(
useSettingsStore,
useUIStore,
useUsersStore,
useWorkflowsStore,
useWorkflowsEEStore,
useProjectsStore,
useRolesStore,
),
isSharingEnabled(): boolean {
return this.settingsStore.isEnterpriseFeatureEnabled[EnterpriseEditionFeature.Sharing];
},
modalTitle(): string {
if (this.isHomeTeamProject) {
return this.$locale.baseText('workflows.shareModal.title.static', {
interpolate: { projectName: this.workflow.homeProject?.name ?? '' },
});
}
const { data } = props;
return this.$locale.baseText(
this.isSharingEnabled
? (this.uiStore.contextBasedTranslationKeys.workflows.sharing.title as BaseTextKey)
: (this.uiStore.contextBasedTranslationKeys.workflows.sharing.unavailable
.title as BaseTextKey),
{
interpolate: { name: this.workflow.name },
},
);
},
workflow(): IWorkflowDb {
return this.data.id === PLACEHOLDER_EMPTY_WORKFLOW_ID
? this.workflowsStore.workflow
: this.workflowsStore.workflowsById[this.data.id];
},
currentUser(): IUser | null {
return this.usersStore.currentUser;
},
workflowPermissions() {
return getResourcePermissions(this.workflow?.scopes).workflow;
},
workflowOwnerName(): string {
return this.workflowsEEStore.getWorkflowOwnerName(`${this.workflow.id}`);
},
projects(): ProjectListItem[] {
return this.projectsStore.personalProjects.filter(
(project) => project.id !== this.workflow.homeProject?.id,
);
},
isHomeTeamProject(): boolean {
return this.workflow.homeProject?.type === ProjectTypes.Team;
},
numberOfMembersInHomeTeamProject(): number {
return this.teamProject?.relations.length ?? 0;
},
workflowRoleTranslations(): Record<string, string> {
return {
'workflow:editor': this.$locale.baseText('workflows.shareModal.role.editor'),
};
},
workflowRoles(): RoleMap['workflow'] {
return this.rolesStore.processedWorkflowRoles.map(({ role, scopes, licensed }) => ({
role,
name: this.workflowRoleTranslations[role],
scopes,
licensed,
}));
},
},
watch: {
sharedWithProjects: {
handler() {
this.isDirty = true;
},
deep: true,
},
},
async mounted() {
await this.initialize();
},
methods: {
onProjectAdded(project: ProjectSharingData) {
this.trackTelemetry('User selected sharee to add', {
project_id_sharer: this.workflow.homeProject?.id,
project_id_sharee: project.id,
});
},
onProjectRemoved(project: ProjectSharingData) {
this.trackTelemetry('User selected sharee to remove', {
project_id_sharer: this.workflow.homeProject?.id,
project_id_sharee: project.id,
});
},
async onSave() {
if (this.loading) {
return;
}
const workflowsStore = useWorkflowsStore();
const settingsStore = useSettingsStore();
const uiStore = useUIStore();
const usersStore = useUsersStore();
const workflowsEEStore = useWorkflowsEEStore();
const projectsStore = useProjectsStore();
const rolesStore = useRolesStore();
this.loading = true;
const toast = useToast();
const message = useMessage();
const pageRedirectionHelper = usePageRedirectionHelper();
const i18n = useI18n();
const saveWorkflowPromise = async () => {
return await new Promise<string>((resolve) => {
if (this.workflow.id === PLACEHOLDER_EMPTY_WORKFLOW_ID) {
nodeViewEventBus.emit('saveWorkflow', () => {
resolve(this.workflow.id);
});
} else {
resolve(this.workflow.id);
}
});
};
const workflow = ref(
data.id === PLACEHOLDER_EMPTY_WORKFLOW_ID
? workflowsStore.workflow
: workflowsStore.workflowsById[data.id],
);
const loading = ref(true);
const isDirty = ref(false);
const modalBus = createEventBus();
const sharedWithProjects = ref([
...(workflow.value.sharedWithProjects ?? []),
] as ProjectSharingData[]);
const teamProject = ref(null as Project | null);
try {
const workflowId = await saveWorkflowPromise();
await this.workflowsEEStore.saveWorkflowSharedWith({
workflowId,
sharedWithProjects: this.sharedWithProjects,
});
const isSharingEnabled = computed(
() => settingsStore.isEnterpriseFeatureEnabled[EnterpriseEditionFeature.Sharing],
);
this.showMessage({
title: this.$locale.baseText('workflows.shareModal.onSave.success.title'),
type: 'success',
});
this.isDirty = false;
} catch (error) {
this.showError(error, this.$locale.baseText('workflows.shareModal.onSave.error.title'));
} finally {
this.modalBus.emit('close');
this.loading = false;
}
const isHomeTeamProject = computed(() => workflow.value.homeProject?.type === ProjectTypes.Team);
const modalTitle = computed(() => {
if (isHomeTeamProject.value) {
return i18n.baseText('workflows.shareModal.title.static', {
interpolate: { projectName: workflow.value.homeProject?.name ?? '' },
});
}
return i18n.baseText(
isSharingEnabled.value
? (uiStore.contextBasedTranslationKeys.workflows.sharing.title as BaseTextKey)
: (uiStore.contextBasedTranslationKeys.workflows.sharing.unavailable.title as BaseTextKey),
{
interpolate: { name: workflow.value.name },
},
async onCloseModal() {
if (this.isDirty) {
const shouldSave = await this.confirm(
this.$locale.baseText('workflows.shareModal.saveBeforeClose.message'),
this.$locale.baseText('workflows.shareModal.saveBeforeClose.title'),
{
type: 'warning',
confirmButtonText: this.$locale.baseText(
'workflows.shareModal.saveBeforeClose.confirmButtonText',
),
cancelButtonText: this.$locale.baseText(
'workflows.shareModal.saveBeforeClose.cancelButtonText',
),
},
);
if (shouldSave === MODAL_CONFIRM) {
return await this.onSave();
}
}
return true;
},
goToUsersSettings() {
this.$router.push({ name: VIEWS.USERS_SETTINGS }).catch((failure) => {
if (!isNavigationFailure(failure)) {
console.error(failure);
}
});
this.modalBus.emit('close');
},
trackTelemetry(eventName: string, data: ITelemetryTrackProperties) {
this.$telemetry.track(eventName, {
workflow_id: this.workflow.id,
...data,
});
},
goToUpgrade() {
void this.goToUpgrade('workflow_sharing', 'upgrade-workflow-sharing');
},
async initialize() {
if (this.isSharingEnabled) {
await Promise.all([this.usersStore.fetchUsers(), this.projectsStore.getAllProjects()]);
if (this.workflow.id !== PLACEHOLDER_EMPTY_WORKFLOW_ID) {
await this.workflowsStore.fetchWorkflow(this.workflow.id);
}
if (this.isHomeTeamProject && this.workflow.homeProject) {
this.teamProject = await this.projectsStore.fetchProject(this.workflow.homeProject.id);
}
}
this.loading = false;
},
},
);
});
const workflowPermissions = computed(() => getResourcePermissions(workflow.value?.scopes).workflow);
const workflowOwnerName = computed(() =>
workflowsEEStore.getWorkflowOwnerName(`${workflow.value.id}`),
);
const projects = computed(() =>
projectsStore.personalProjects.filter((project) => project.id !== workflow.value.homeProject?.id),
);
const numberOfMembersInHomeTeamProject = computed(() => teamProject.value?.relations.length ?? 0);
const workflowRoleTranslations = computed(() => ({
'workflow:editor': i18n.baseText('workflows.shareModal.role.editor'),
'workflow:owner': '',
}));
const workflowRoles = computed(() =>
rolesStore.processedWorkflowRoles.map(({ role, scopes, licensed }) => ({
role,
name: workflowRoleTranslations.value[role],
scopes,
licensed,
})),
);
const trackTelemetry = (eventName: string, data: ITelemetryTrackProperties) => {
telemetry.track(eventName, {
workflow_id: workflow.value.id,
...data,
});
};
const onProjectAdded = (project: ProjectSharingData) => {
trackTelemetry('User selected sharee to add', {
project_id_sharer: workflow.value.homeProject?.id,
project_id_sharee: project.id,
});
};
const onProjectRemoved = (project: ProjectSharingData) => {
trackTelemetry('User selected sharee to remove', {
project_id_sharer: workflow.value.homeProject?.id,
project_id_sharee: project.id,
});
};
const onSave = async () => {
if (loading.value) {
return;
}
loading.value = true;
const saveWorkflowPromise = async () => {
return await new Promise<string>((resolve) => {
if (workflow.value.id === PLACEHOLDER_EMPTY_WORKFLOW_ID) {
nodeViewEventBus.emit('saveWorkflow', () => {
resolve(workflow.value.id);
});
} else {
resolve(workflow.value.id);
}
});
};
try {
const workflowId = await saveWorkflowPromise();
await workflowsEEStore.saveWorkflowSharedWith({
workflowId,
sharedWithProjects: sharedWithProjects.value,
});
toast.showMessage({
title: i18n.baseText('workflows.shareModal.onSave.success.title'),
});
isDirty.value = false;
} catch (error) {
toast.showError(error, i18n.baseText('workflows.shareModal.onSave.error.title'));
} finally {
modalBus.emit('close');
loading.value = false;
}
};
const onCloseModal = async () => {
if (isDirty.value) {
const shouldSave = await message.confirm(
i18n.baseText('workflows.shareModal.saveBeforeClose.message'),
i18n.baseText('workflows.shareModal.saveBeforeClose.title'),
{
type: 'warning',
confirmButtonText: i18n.baseText('workflows.shareModal.saveBeforeClose.confirmButtonText'),
cancelButtonText: i18n.baseText('workflows.shareModal.saveBeforeClose.cancelButtonText'),
},
);
if (shouldSave === MODAL_CONFIRM) {
return await onSave();
}
}
return true;
};
const goToUpgrade = () => {
void pageRedirectionHelper.goToUpgrade('workflow_sharing', 'upgrade-workflow-sharing');
};
const initialize = async () => {
if (isSharingEnabled.value) {
await Promise.all([usersStore.fetchUsers(), projectsStore.getAllProjects()]);
if (workflow.value.id !== PLACEHOLDER_EMPTY_WORKFLOW_ID) {
await workflowsStore.fetchWorkflow(workflow.value.id);
}
if (isHomeTeamProject.value && workflow.value.homeProject) {
teamProject.value = await projectsStore.fetchProject(workflow.value.homeProject.id);
}
}
loading.value = false;
};
onMounted(async () => {
await initialize();
});
watch(
sharedWithProjects,
() => {
isDirty.value = true;
},
{ deep: true },
);
</script>
<template>
@ -272,7 +238,7 @@ export default defineComponent({
<div v-if="!isSharingEnabled" :class="$style.container">
<n8n-text>
{{
$locale.baseText(
i18n.baseText(
uiStore.contextBasedTranslationKeys.workflows.sharing.unavailable.description.modal,
)
}}
@ -285,7 +251,7 @@ export default defineComponent({
class="mb-s"
>
{{
$locale.baseText('workflows.shareModal.info.sharee', {
i18n.baseText('workflows.shareModal.info.sharee', {
interpolate: { workflowOwnerName },
})
}}
@ -299,7 +265,7 @@ export default defineComponent({
:roles="workflowRoles"
:readonly="!workflowPermissions.share"
:static="isHomeTeamProject || !workflowPermissions.share"
:placeholder="$locale.baseText('workflows.shareModal.select.placeholder')"
:placeholder="i18n.baseText('workflows.shareModal.select.placeholder')"
@project-added="onProjectAdded"
@project-removed="onProjectRemoved"
/>
@ -311,7 +277,7 @@ export default defineComponent({
<template #members>
<strong>
{{
$locale.baseText('workflows.shareModal.info.members.number', {
i18n.baseText('workflows.shareModal.info.members.number', {
interpolate: {
number: String(numberOfMembersInHomeTeamProject),
},
@ -344,9 +310,7 @@ export default defineComponent({
<div v-if="!isSharingEnabled" :class="$style.actionButtons">
<n8n-button @click="goToUpgrade">
{{
$locale.baseText(
uiStore.contextBasedTranslationKeys.workflows.sharing.unavailable.button,
)
i18n.baseText(uiStore.contextBasedTranslationKeys.workflows.sharing.unavailable.button)
}}
</n8n-button>
</div>
@ -356,10 +320,10 @@ export default defineComponent({
:class="$style.actionButtons"
>
<n8n-text v-show="isDirty" color="text-light" size="small" class="mr-xs">
{{ $locale.baseText('workflows.shareModal.changesHint') }}
{{ i18n.baseText('workflows.shareModal.changesHint') }}
</n8n-text>
<n8n-button v-if="isHomeTeamProject" type="secondary" @click="modalBus.emit('close')">
{{ $locale.baseText('generic.close') }}
{{ i18n.baseText('generic.close') }}
</n8n-button>
<n8n-button
v-else
@ -369,7 +333,7 @@ export default defineComponent({
data-test-id="workflow-sharing-modal-save-button"
@click="onSave"
>
{{ $locale.baseText('workflows.shareModal.save') }}
{{ i18n.baseText('workflows.shareModal.save') }}
</n8n-button>
</enterprise-edition>
</template>

View file

@ -221,6 +221,8 @@ export const NODES_USING_CODE_NODE_EDITOR = [
AI_TRANSFORM_NODE_TYPE,
];
export const NODE_POSITION_CONFLICT_ALLOWLIST = [STICKY_NODE_TYPE];
export const PIN_DATA_NODE_TYPES_DENYLIST = [SPLIT_IN_BATCHES_NODE_TYPE, STICKY_NODE_TYPE];
export const OPEN_URL_PANEL_TRIGGER_NODE_TYPES = [

View file

@ -2072,6 +2072,7 @@
"ndv.search.noMatch.title": "No matching items",
"ndv.search.noNodeMatch.title": "No matching nodes",
"ndv.search.noMatch.description": "Try changing or {link} the filter to see more",
"ndv.search.noMatchSchema.description": "To search field contents rather than just names, use Table or JSON view",
"ndv.search.noMatch.description.link": "clearing",
"ndv.search.items": "{matched} of {total} item | {matched} of {total} items",
"updatesPanel.andIs": "and is",

View file

@ -1,10 +1,12 @@
import { generateOffsets, getGenericHints } from './nodeViewUtils';
import { generateOffsets, getGenericHints, getNewNodePosition } from './nodeViewUtils';
import type { INode, INodeTypeDescription, INodeExecutionData, Workflow } from 'n8n-workflow';
import type { INodeUi } from '@/Interface';
import type { INodeUi, XYPosition } from '@/Interface';
import { NodeHelpers } from 'n8n-workflow';
import { describe, it, expect, beforeEach } from 'vitest';
import { mock, type MockProxy } from 'vitest-mock-extended';
import { SET_NODE_TYPE, STICKY_NODE_TYPE } from '@/constants';
import { createTestNode } from '@/__tests__/mocks';
describe('getGenericHints', () => {
let mockWorkflowNode: MockProxy<INode>;
@ -169,3 +171,57 @@ describe('generateOffsets', () => {
expect(result).toEqual([-580, -460, -340, -220, -100, 100, 220, 340, 460, 580]);
});
});
describe('getNewNodePosition', () => {
it('should return the new position when there are no conflicts', () => {
const nodes: INodeUi[] = [];
const newPosition: XYPosition = [100, 100];
const result = getNewNodePosition(nodes, newPosition);
expect(result).toEqual([100, 100]);
});
it('should adjust the position to the closest grid size', () => {
const nodes: INodeUi[] = [];
const newPosition: XYPosition = [105, 115];
const result = getNewNodePosition(nodes, newPosition);
expect(result).toEqual([120, 120]);
});
it('should move the position to avoid conflicts', () => {
const nodes: INodeUi[] = [
createTestNode({ id: '1', position: [100, 100], type: SET_NODE_TYPE }),
];
const newPosition: XYPosition = [100, 100];
const result = getNewNodePosition(nodes, newPosition);
expect(result).toEqual([180, 180]);
});
it('should skip nodes in the conflict allowlist', () => {
const nodes: INodeUi[] = [
createTestNode({ id: '1', position: [100, 100], type: STICKY_NODE_TYPE }),
];
const newPosition: XYPosition = [100, 100];
const result = getNewNodePosition(nodes, newPosition);
expect(result).toEqual([100, 100]);
});
it('should use the provided move position to resolve conflicts', () => {
const nodes: INodeUi[] = [
createTestNode({ id: '1', position: [100, 100], type: SET_NODE_TYPE }),
];
const newPosition: XYPosition = [100, 100];
const movePosition: XYPosition = [50, 50];
const result = getNewNodePosition(nodes, newPosition, movePosition);
expect(result).toEqual([200, 200]);
});
it('should handle multiple conflicts correctly', () => {
const nodes: INodeUi[] = [
createTestNode({ id: '1', position: [100, 100], type: SET_NODE_TYPE }),
createTestNode({ id: '2', position: [140, 140], type: SET_NODE_TYPE }),
];
const newPosition: XYPosition = [100, 100];
const result = getNewNodePosition(nodes, newPosition);
expect(result).toEqual([220, 220]);
});
});

View file

@ -2,6 +2,7 @@ import { isNumber, isValidNodeConnectionType } from '@/utils/typeGuards';
import {
LIST_LIKE_NODE_OPERATIONS,
NODE_OUTPUT_DEFAULT_KEY,
NODE_POSITION_CONFLICT_ALLOWLIST,
SET_NODE_TYPE,
SPLIT_IN_BATCHES_NODE_TYPE,
STICKY_NODE_TYPE,
@ -582,6 +583,11 @@ export const getNewNodePosition = (
conflictFound = false;
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
if (NODE_POSITION_CONFLICT_ALLOWLIST.includes(node.type)) {
continue;
}
if (!canUsePosition(node.position, targetPosition)) {
conflictFound = true;
break;

View file

@ -1,4 +1,9 @@
import type { ICredentialType, INodeProperties } from 'n8n-workflow';
import type {
IAuthenticateGeneric,
ICredentialTestRequest,
ICredentialType,
INodeProperties,
} from 'n8n-workflow';
export class OuraApi implements ICredentialType {
name = 'ouraApi';
@ -16,4 +21,20 @@ export class OuraApi implements ICredentialType {
default: '',
},
];
authenticate: IAuthenticateGeneric = {
type: 'generic',
properties: {
headers: {
Authorization: '=Bearer {{$credentials.accessToken}}',
},
},
};
test: ICredentialTestRequest = {
request: {
baseURL: 'https://api.ouraring.com',
url: '/v2/usercollection/personal_info',
},
};
}

View file

@ -31,6 +31,14 @@ export class AiTransform implements INodeType {
inputs: [NodeConnectionType.Main],
outputs: [NodeConnectionType.Main],
parameterPane: 'wide',
hints: [
{
message:
"This node doesn't have access to the contents of binary files. To use those contents here, use the 'Extract from File' node first.",
displayCondition: '={{ $input.all().some(i => i.binary) }}',
location: 'outputPane',
},
],
properties: [
{
displayName: 'Instructions',

View file

@ -108,7 +108,7 @@ export class Code implements INodeType {
: 'javaScript';
const codeParameterName = language === 'python' ? 'pythonCode' : 'jsCode';
if (!runnersConfig.disabled && language === 'javaScript') {
if (runnersConfig.enabled && language === 'javaScript') {
const code = this.getNodeParameter(codeParameterName, 0) as string;
const sandbox = new JsTaskRunnerSandbox(code, nodeMode, workflowMode, this);

View file

@ -235,7 +235,7 @@ export const bucketOperations: INodeProperties[] = [
preSend: [parseJSONBody],
},
},
action: 'Create a new Bucket',
action: 'Update the metadata of a Bucket',
},
],
default: 'getAll',

View file

@ -4,7 +4,7 @@ import type {
IHookFunctions,
ILoadOptionsFunctions,
JsonObject,
IRequestOptions,
IHttpRequestOptions,
IHttpRequestMethods,
} from 'n8n-workflow';
import { NodeApiError } from 'n8n-workflow';
@ -18,15 +18,11 @@ export async function ouraApiRequest(
uri?: string,
option: IDataObject = {},
) {
const credentials = await this.getCredentials('ouraApi');
let options: IRequestOptions = {
headers: {
Authorization: `Bearer ${credentials.accessToken}`,
},
let options: IHttpRequestOptions = {
method,
qs,
body,
uri: uri || `https://api.ouraring.com/v1${resource}`,
url: uri ?? `https://api.ouraring.com/v2${resource}`,
json: true,
};
@ -41,7 +37,7 @@ export async function ouraApiRequest(
options = Object.assign({}, options, option);
try {
return await this.helpers.request(options);
return await this.helpers.httpRequestWithAuthentication.call(this, 'ouraApi', options);
} catch (error) {
throw new NodeApiError(this.getNode(), error as JsonObject);
}

View file

@ -63,94 +63,126 @@ export class Oura implements INodeType {
const length = items.length;
let responseData;
const returnData: IDataObject[] = [];
const returnData: INodeExecutionData[] = [];
const resource = this.getNodeParameter('resource', 0);
const operation = this.getNodeParameter('operation', 0);
for (let i = 0; i < length; i++) {
if (resource === 'profile') {
// *********************************************************************
// profile
// *********************************************************************
try {
if (resource === 'profile') {
// *********************************************************************
// profile
// *********************************************************************
// https://cloud.ouraring.com/docs/personal-info
// https://cloud.ouraring.com/docs/personal-info
if (operation === 'get') {
// ----------------------------------
// profile: get
// ----------------------------------
if (operation === 'get') {
// ----------------------------------
// profile: get
// ----------------------------------
responseData = await ouraApiRequest.call(this, 'GET', '/userinfo');
}
} else if (resource === 'summary') {
// *********************************************************************
// summary
// *********************************************************************
// https://cloud.ouraring.com/docs/daily-summaries
const qs: IDataObject = {};
const { start, end } = this.getNodeParameter('filters', i) as {
start: string;
end: string;
};
const returnAll = this.getNodeParameter('returnAll', 0);
if (start) {
qs.start = moment(start).format('YYYY-MM-DD');
}
if (end) {
qs.end = moment(end).format('YYYY-MM-DD');
}
if (operation === 'getActivity') {
// ----------------------------------
// profile: getActivity
// ----------------------------------
responseData = await ouraApiRequest.call(this, 'GET', '/activity', {}, qs);
responseData = responseData.activity;
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
responseData = await ouraApiRequest.call(this, 'GET', '/usercollection/personal_info');
}
} else if (operation === 'getReadiness') {
// ----------------------------------
// profile: getReadiness
// ----------------------------------
} else if (resource === 'summary') {
// *********************************************************************
// summary
// *********************************************************************
responseData = await ouraApiRequest.call(this, 'GET', '/readiness', {}, qs);
responseData = responseData.readiness;
// https://cloud.ouraring.com/docs/daily-summaries
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
const qs: IDataObject = {};
const { start, end } = this.getNodeParameter('filters', i) as {
start: string;
end: string;
};
const returnAll = this.getNodeParameter('returnAll', 0);
if (start) {
qs.start_date = moment(start).format('YYYY-MM-DD');
}
} else if (operation === 'getSleep') {
// ----------------------------------
// profile: getSleep
// ----------------------------------
responseData = await ouraApiRequest.call(this, 'GET', '/sleep', {}, qs);
responseData = responseData.sleep;
if (end) {
qs.end_date = moment(end).format('YYYY-MM-DD');
}
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
if (operation === 'getActivity') {
// ----------------------------------
// profile: getActivity
// ----------------------------------
responseData = await ouraApiRequest.call(
this,
'GET',
'/usercollection/daily_activity',
{},
qs,
);
responseData = responseData.data;
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
}
} else if (operation === 'getReadiness') {
// ----------------------------------
// profile: getReadiness
// ----------------------------------
responseData = await ouraApiRequest.call(
this,
'GET',
'/usercollection/daily_readiness',
{},
qs,
);
responseData = responseData.data;
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
}
} else if (operation === 'getSleep') {
// ----------------------------------
// profile: getSleep
// ----------------------------------
responseData = await ouraApiRequest.call(
this,
'GET',
'/usercollection/daily_sleep',
{},
qs,
);
responseData = responseData.data;
if (!returnAll) {
const limit = this.getNodeParameter('limit', 0);
responseData = responseData.splice(0, limit);
}
}
}
const executionData = this.helpers.constructExecutionMetaData(
this.helpers.returnJsonArray(responseData as IDataObject[]),
{ itemData: { item: i } },
);
returnData.push(...executionData);
} catch (error) {
if (this.continueOnFail()) {
const executionErrorData = this.helpers.constructExecutionMetaData(
this.helpers.returnJsonArray({ error: error.message }),
{ itemData: { item: i } },
);
returnData.push(...executionErrorData);
continue;
}
throw error;
}
Array.isArray(responseData)
? returnData.push(...(responseData as IDataObject[]))
: returnData.push(responseData as IDataObject);
}
return [this.helpers.returnJsonArray(returnData)];
return [returnData];
}
}

View file

@ -0,0 +1,8 @@
export const profileResponse = {
id: 'some-id',
age: 30,
weight: 168,
height: 80,
biological_sex: 'male',
email: 'nathan@n8n.io',
};

View file

@ -0,0 +1,76 @@
import type {
IExecuteFunctions,
IHookFunctions,
ILoadOptionsFunctions,
IHttpRequestMethods,
INode,
} from 'n8n-workflow';
import nock from 'nock';
import { setup, equalityTest, workflowToTests, getWorkflowFilenames } from '@test/nodes/Helpers';
import { profileResponse } from './apiResponses';
import { ouraApiRequest } from '../GenericFunctions';
const node: INode = {
id: '2cdb46cf-b561-4537-a982-b8d26dd7718b',
name: 'Oura',
type: 'n8n-nodes-base.oura',
typeVersion: 1,
position: [0, 0],
parameters: {
resource: 'profile',
operation: 'get',
},
};
const mockThis = {
helpers: {
httpRequestWithAuthentication: jest
.fn()
.mockResolvedValue({ statusCode: 200, data: profileResponse }),
},
getNode() {
return node;
},
getNodeParameter: jest.fn(),
} as unknown as IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions;
describe('Oura', () => {
describe('ouraApiRequest', () => {
it('should make an authenticated API request to Oura', async () => {
const method: IHttpRequestMethods = 'GET';
const resource = '/usercollection/personal_info';
await ouraApiRequest.call(mockThis, method, resource);
expect(mockThis.helpers.httpRequestWithAuthentication).toHaveBeenCalledWith('ouraApi', {
method: 'GET',
url: 'https://api.ouraring.com/v2/usercollection/personal_info',
json: true,
});
});
});
describe('Run Oura workflow', () => {
const workflows = getWorkflowFilenames(__dirname);
const tests = workflowToTests(workflows);
beforeAll(() => {
nock.disableNetConnect();
nock('https://api.ouraring.com/v2')
.get('/usercollection/personal_info')
.reply(200, profileResponse);
});
afterAll(() => {
nock.restore();
});
const nodeTypes = setup(tests);
for (const testData of tests) {
test(testData.description, async () => await equalityTest(testData, nodeTypes));
}
});
});

View file

@ -0,0 +1,86 @@
{
"name": "Oura Test Workflow",
"nodes": [
{
"parameters": {},
"id": "c1e3b825-a9a8-4def-986b-9108d9441992",
"name": "When clicking Test workflow",
"type": "n8n-nodes-base.manualTrigger",
"position": [720, 400],
"typeVersion": 1
},
{
"parameters": {
"resource": "profile"
},
"id": "7969bf78-9343-4f81-8f79-dc415a60e168",
"name": "Oura",
"type": "n8n-nodes-base.oura",
"typeVersion": 1,
"position": [940, 400],
"credentials": {
"ouraApi": {
"id": "r083EOdhFatkVvFy",
"name": "Oura account"
}
}
},
{
"parameters": {},
"id": "9b97fa0e-51a6-41d3-8a7d-cff0531e5527",
"name": "No Operation, do nothing",
"type": "n8n-nodes-base.noOp",
"typeVersion": 1,
"position": [1140, 400]
}
],
"pinData": {
"No Operation, do nothing": [
{
"json": {
"id": "some-id",
"age": 30,
"weight": 168,
"height": 80,
"biological_sex": "male",
"email": "nathan@n8n.io"
}
}
]
},
"connections": {
"When clicking Test workflow": {
"main": [
[
{
"node": "Oura",
"type": "main",
"index": 0
}
]
]
},
"Oura": {
"main": [
[
{
"node": "No Operation, do nothing",
"type": "main",
"index": 0
}
]
]
}
},
"active": false,
"settings": {
"executionOrder": "v1"
},
"versionId": "bd108f46-f6fc-4c22-8655-ade2f51c4b33",
"meta": {
"templateCredsSetupCompleted": true,
"instanceId": "0fa937d34dcabeff4bd6480d3b42cc95edf3bc20e6810819086ef1ce2623639d"
},
"id": "SrUileWU90mQeo02",
"tags": []
}