<template>
  <v-layout wrap>
    <v-flex xs12 sm6 md4>
      <v-menu
        ref="menu"
        v-model="menu"
        :close-on-content-click="false"
        :return-value.sync="date"
        transition="scale-transition"
        offset-y
        full-width
        min-width="290px"
      >
        <template v-slot:activator="{ on }">
          <v-text-field
            v-model="date"
            label="Picker in menu"
            prepend-icon="event"
            readonly
            v-on="on"
          ></v-text-field>
        </template>
        <v-date-picker v-model="date" no-title scrollable>
          <v-spacer></v-spacer>
          <v-btn text color="primary" @click="menu = false">Cancel</v-btn>
          <v-btn text color="primary" @click="$refs.menu.save(date)">OK</v-btn>
        </v-date-picker>
      </v-menu>
    </v-flex>
    <v-spacer></v-spacer>
    <v-flex xs12 sm6 md4>
      <v-dialog
        ref="dialog"
        v-model="modal"
        :return-value.sync="date"
        persistent
        full-width
        width="290px"
      >
        <template v-slot:activator="{ on }">
          <v-text-field
            v-model="date"
            label="Picker in dialog"
            prepend-icon="event"
            readonly
            v-on="on"
          ></v-text-field>
        </template>
        <v-date-picker v-model="date" scrollable>
          <v-spacer></v-spacer>
          <v-btn text color="primary" @click="modal = false">Cancel</v-btn>
          <v-btn text color="primary" @click="$refs.dialog.save(date)">OK</v-btn>
        </v-date-picker>
      </v-dialog>
    </v-flex>
    <v-flex xs12 sm6 md4>
      <v-menu
        v-model="menu2"
        :close-on-content-click="false"
        :nudge-right="40"
        transition="scale-transition"
        offset-y
        full-width
        min-width="290px"
      >
        <template v-slot:activator="{ on }">
          <v-text-field
            v-model="date"
            label="Picker without buttons"
            prepend-icon="event"
            readonly
            v-on="on"
          ></v-text-field>
        </template>
        <v-date-picker v-model="date" @input="menu2 = false"></v-date-picker>
      </v-menu>
    </v-flex>
    <v-spacer></v-spacer>
  </v-layout>
</template>

<script>
  export default {
    data: () => ({
      date: new Date().toISOString().substr(0, 10),
      menu: false,
      modal: false,
      menu2: false,
    }),
  }
</script>


.v-toolbar--prominent
.v-toolbar__content
align-items: flex-start
.v-toolbar__title
align-self: flex-end
font-size: 1.5rem

<template>
  <v-container>
    <v-btn
      large
      color="red"
      dark
      fab
      fixed
      bottom
      right
      @click="() => landscape = !landscape"
    >
      <v-icon small>
        {{ landscape ? 'mdi-phone-rotate-portrait' : 'mdi-phone-rotate-landscape' }}
      </v-icon>
    </v-btn>

    <v-layout column>
      Month pickers

      <core-title>
        Month pickers
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            type="month"
          />
        </v-layout>
      </core-section>

      <core-title>
        Landscape
      </core-title>
      <core-section center>
        <v-date-picker
          v-model="model"
          type="month"
          landscape
        />
      </core-section>

      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-flex text-center>
            <core-title>
              Readonly
            </core-title>
            <v-date-picker
              v-model="model"
              type="month"
              :landscape="landscape"
              readonly
            />
          </v-flex>
          <v-flex text-center>
            <core-title>
              Disabled
            </core-title>
            <v-date-picker
              v-model="model"
              type="month"
              :landscape="landscape"
              disabled
            />
          </v-flex>
          <v-flex text-center>
            <core-title>
              Reactive
            </core-title>
            <v-date-picker
              v-model="model"
              type="month"
              :landscape="landscape"
              reactive
            />
          </v-flex>
        </v-layout>
      </core-section>

      <core-title>
        Color
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="success"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="red lighten-2"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="blue"
          />
        </v-layout>
      </core-section>

      <core-title>
        Header colors
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            header-color="success"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            header-color="red lighten-2"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            header-color="blue"
          />
        </v-layout>
      </core-section>

      <core-title>
        Using header colors with colors
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="red lighten-2"
            header-color="success"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="error"
            header-color="red lighten-2"
          />
          <v-date-picker
            v-model="model"
            type="month"
            :landscape="landscape"
            class="mt-6"
            color="teal"
            header-color="blue"
          />
        </v-layout>
      </core-section>

      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-flex text-center>
            <core-title>
              Allowed months: min/max
            </core-title>
            <v-date-picker
              v-model="modelMM"
              type="month"
              :landscape="landscape"
              min="2018-11"
              max="2019-08"
            />
          </v-flex>
          <v-flex text-center>
            <core-title>
              Allowed dates: function
            </core-title>
            <v-date-picker
              v-model="modelMM"
              type="month"
              :landscape="landscape"
              :allowed-dates="val => parseInt(val.split('-')[1], 10) % 2 === 1"
            />
          </v-flex>
        </v-layout>
      </core-section>

      <core-title>
        Multiple
      </core-title>
      <core-section>
        <v-layout
          column
          align-center
        >
          <v-date-picker
            v-model="months"
            :landscape="landscape"
            type="month"
            multiple
          />

          <v-combobox
            v-model="months"
            multiple
            chips
            small-chips
            label="Selected months"
            prepend-icon="mdi-calendar"
            readonly
            clearable
          />
        </v-layout>
      </core-section>

      <core-title>
        Custom width
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            class="mt-4"
            type="month"
            width="150"
          />
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            class="mt-4"
            type="month"
            width="290"
          />
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            class="mt-4"
            type="month"
            width="400"
          />
        </v-layout>
      </core-section>

      <core-title>
        Full width
      </core-title>
      <core-section>
        <v-layout
          wrap
          align-center
          justify-space-around
        >
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            class="mt-4"
            full-width
            type="month"
          />
        </v-layout>
      </core-section>

      <core-title>
        Events
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
        >

              Defined by array

            <v-date-picker
              v-model="model"
              type="month"
              :landscape="landscape"
              :events="arrayEvents"
              event-color="green lighten-1"
            />

              Defined by function

            <v-date-picker
              v-model="model"
              type="month"
              :landscape="landscape"
              :event-color="date => date[6] % 2 ? 'red' : 'yellow'"
              :events="functionEvents"
            />

        </v-layout>
      </core-section>

      <core-title>
        i18n
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            type="month"
            locale="th"
            class="mt-4"
          />
          <v-date-picker
            v-model="model"
            :landscape="landscape"
            type="month"
            locale="sv-se"
            class="mt-4"
          />
        </v-layout>
      </core-section>

      <core-title>
        Custom icons
      </core-title>
      <core-section center>
        <v-date-picker
          v-model="model"
          :landscape="landscape"
          type="month"
          year-icon="mdi-calendar-blank"
          prev-icon="mdi-skip-previous"
          next-icon="mdi-skip-next"
        />
      </core-section>

      <core-title>
        Current month indicator
      </core-title>
      <core-section>
        <v-layout
          wrap
          justify-space-around
          align-center
        >

            <v-date-picker
              v-model="model"
              :landscape="landscape"
              :show-current="false"
              type="month"
            />

            <v-date-picker
              v-model="model"
              :landscape="landscape"
              type="month"
              show-current="2019-07"
            />

        </v-layout>
      </core-section>
    </v-layout>
  </v-container>
</template>


padding-top: 6px
&:not(.v-toolbar--bottom)
.v-toolbar__title
align-self: flex-end
padding-bottom: 6px
padding-top: 0

@import '../../styles/styles.sass'
@import './_variables.scss'

// Block
.v-app-bar
  +bootable()

// Modifier
.v-app-bar.v-app-bar--fixed
  position: fixed
  top: 0
  z-index: 5

.v-app-bar.v-app-bar--hide-shadow
  +elevation(0)

.v-app-bar--fade-img-on-scroll
  .v-toolbar__image .v-image__image
    transition: $app-bar-transition

.v-app-bar.v-toolbar--prominent.v-app-bar--shrink-on-scroll
  .v-toolbar__content
    will-change: height

  .v-toolbar__image
    will-change: opacity

  &.v-app-bar--collapse-on-scroll
    .v-toolbar__extension
      display: none

  &.v-app-bar--is-scrolled
    .v-toolbar__title
      padding-bottom: $app-bar-scrolled-title-padding-bottom

.v-app-bar.v-app-bar--shrink-on-scroll
  .v-toolbar__title
    font-size: inherit


@import '../../styles/styles.sass'

.v-color-picker__canvas
  $root: &
  position: relative
  overflow: hidden
  contain: strict

  &-dot
    position: absolute
    top: 0
    left: 0
    width: 15px
    height: 15px
    background: transparent
    border-radius: 50%
    box-shadow: 0px 0px 0px 1.5px rgba(255,255,255,1), inset 0px 0px 1px 1.5px rgba(0,0,0,0.3)

    &--disabled
      box-shadow: 0px 0px 0px 1.5px rgba(255,255,255,0.7), inset 0px 0px 1px 1.5px rgba(0,0,0,0.3)

    #{$root}:hover &
      will-change: transform


throw new Exception('Session not found', 404, Exception::TYPE_SESSION_NOT_FOUND);

keep keep keep keep replace keep keep keep keep keep

throw new Exception('Session not found', 404, Exception::USER_SESSION_NOT_FOUND);

<?php

/**
 * List of server wide error codes and their respective messages.
 */

use Appwrite\Extend\Exception;

return [
    /** General Errors */
    Exception::UNKNOWN_ORIGIN => [
        'name' => Exception::UNKNOWN_ORIGIN,
        'description' => 'The request originated from a non-whitelisted origin. If you trust this origin, please add it as a platform in the Appwrite console.',
        'statusCode' => 403,
    ],
    Exception::SERVICE_DISABLED => [
        'name' => Exception::SERVICE_DISABLED,
        'description' => 'The requested service is disabled. You can enable/disable a service from the Appwrite console or by contacting the project owner.',
        'statusCode' => 503,
    ],
    Exception::UNAUTHORIZED_SCOPE => [
        'name' => Exception::UNAUTHORIZED_SCOPE,
        'description' => 'The current user or API key does not have the required scopes to access the requested resource.',
        'statusCode' => 401,
    ],
    Exception::STORAGE_ERROR => [
        'name' => Exception::STORAGE_ERROR,
        'description' => 'Storage error',
        'statusCode' => 500,
    ],
    Exception::RATE_LIMIT_EXCEEDED => [
        'name' => Exception::RATE_LIMIT_EXCEEDED,
        'description' => 'Rate limit for the current endpoint has been exceeded. Please try again after some time.',
        'statusCode' => 429,
    ],
    Exception::SMTP_DISABLED => [
        'name' => Exception::SMTP_DISABLED,
        'description' => 'SMTP is disabled on your Appwrite instance. Please contact your project ',
        'statusCode' => 503,
    ],

    /** Project Errors */
    Exception::PROJECT_NOT_FOUND => [
        'name' => Exception::PROJECT_NOT_FOUND,
        'description' => 'The requested project could not be found. Please check the value of the X-Appwrite-Project header to ensure the correct project ID is being used.',
        'statusCode' => 404,
    ],
    Exception::PROJECT_UNKNOWN => [
        'name' => Exception::PROJECT_UNKNOWN,
        'description' => 'The project ID is either missing or not valid. Please check the value of the X-Appwrite-Project header to ensure the correct project ID is being used.',
        'statusCode' => 400,
    ],

    /** User Errors */
    Exception::USER_COUNT_EXCEEDED => [
        'name' => Exception::USER_COUNT_EXCEEDED,
        'description' => 'The current project has exceeded the maximum number of users. Please check your user limit in the Appwrite console.',
        'statusCode' => 501,
    ],
    Exception::USER_EMAIL_NOT_WHITELISTED => [
        'name' => Exception::USER_EMAIL_NOT_WHITELISTED,
        'description' => 'The user\'s email is not part of the whitelist. Please check the _APP_CONSOLE_WHITELIST_EMAILS environment variable of your Appwrite server.',
        'statusCode' => 401,
    ],
    Exception::USER_PASSWORD_RESET_REQUIRED => [
        'name' => Exception::USER_PASSWORD_RESET_REQUIRED,
        'description' => 'The current user requires a password reset.',
        'statusCode' => 412,
    ],
    Exception::USER_IP_NOT_WHITELISTED => [
        'name' => Exception::USER_IP_NOT_WHITELISTED,
        'description' => 'The user\'s IP address is not part of the whitelist. Please check the _APP_CONSOLE_WHITELIST_IPS environment variable of your Appwrite server.',
        'statusCode' => 401,
    ],
    Exception::USER_INVALID_CREDENTIALS => [
        'name' => Exception::USER_INVALID_CREDENTIALS,
        'description' => 'Invalid credentials. Please check the email and password.',
        'statusCode' => 401,
    ],
    Exception::USER_ALREADY_EXISTS => [
        'name' => Exception::USER_ALREADY_EXISTS,
        'description' => 'A user with the same email ID already exists in your project.',
        'statusCode' => 409,
    ],
    Exception::USER_INVALID_TOKEN => [
        'name' => Exception::USER_INVALID_TOKEN,
        'description' => 'Invalid token.',
        'statusCode' => 401,
    ],
    Exception::USER_BLOCKED => [
        'name' => Exception::USER_BLOCKED,
        'description' => 'The current user has been blocked. Please contact the project administrator for more information.',
        'statusCode' => 401,
    ],
    Exception::USER_ANONYMOUS_CONSOLE_PROHIBITED => [
        'name' => Exception::USER_ANONYMOUS_CONSOLE_PROHIBITED,
        'description' => 'Anonymous users cannot be created for console project.',
        'statusCode' => 401,
    ],
    Exception::USER_SESSION_ALREADY_EXISTS => [
        'name' => Exception::USER_SESSION_ALREADY_EXISTS,
        'description' => 'Cannot create anonymous user when a session is active.',
        'statusCode' => 401,
    ],
    Exception::USER_CREATION_FAILED => [
        'name' => Exception::USER_CREATION_FAILED,
        'description' => 'There was an internal server error while creating the user.',
        'statusCode' => 500,
    ],
    Exception::USER_NOT_FOUND => [
        'name' => Exception::USER_NOT_FOUND,
        'description' => 'User with the requested ID could not be found.',
        'statusCode' => 404,
    ],
    Exception::USER_EMAIL_ALREADY_EXISTS => [
        'name' => Exception::USER_EMAIL_ALREADY_EXISTS,
        'description' => 'Another user with the same email already exists in the current project.',
        'statusCode' => 409,
    ],
    Exception::USER_PASSWORD_MISMATCH => [
        'name' => Exception::USER_PASSWORD_MISMATCH,
        'description' => 'Passwords do not match. Please recheck.',
        'statusCode' => 400,
    ],
    Exception::USER_AUTH_METHOD_UNSUPPORTED => [
        'name' => Exception::USER_AUTH_METHOD_UNSUPPORTED,
        'description' => 'The requested authentication method is either disabled or unsupported.',
        'statusCode' => 501,
    ],

    /** OAuth Errors */
    Exception::OAUTH_PROVIDER_DISABLED => [
        'name' => Exception::OAUTH_PROVIDER_DISABLED,
        'description' => 'The chosen OAuth provider is disabled. Please contact your project administrator for more information.',
        'statusCode' => 412,
    ],
    Exception::OAUTH_PROVIDER_UNSUPPORTED => [
        'name' => Exception::OAUTH_PROVIDER_UNSUPPORTED,
        'description' => 'The chosen OAuth provider is unsupported.',
        'statusCode' => 501,
    ],
    Exception::OAUTH_INVALID_LOGIN_STATE_PARAMS => [
        'name' => Exception::OAUTH_INVALID_LOGIN_STATE_PARAMS,
        'description' => 'Failed to parse the login state params from the OAuth provider.',
        'statusCode' => 500,
    ],
    Exception::OAUTH_INVALID_SUCCESS_URL => [
        'name' => Exception::OAUTH_INVALID_SUCCESS_URL,
        'description' => 'Invalid URL received for OAuth success redirect.',
        'statusCode' => 400,
    ],
    Exception::OAUTH_INVALID_FAILURE_URL => [
        'name' => Exception::OAUTH_INVALID_FAILURE_URL,
        'description' => 'Invalid URL received for OAuth failure redirect.',
        'statusCode' => 400,
    ],
    Exception::OAUTH_ACCESS_TOKEN_FAILED => [
        'name' => Exception::OAUTH_ACCESS_TOKEN_FAILED,
        'description' => 'Failed to obtain access token from the OAuth provider.',
        'statusCode' => 500,
    ],
    Exception::OAUTH_MISSING_USER_ID => [
        'name' => Exception::OAUTH_MISSING_USER_ID,
        'description' => 'Failed to obtain user id from the OAuth provider.',
        'statusCode' => 400,
    ]
];


require 'appwrite'

client = Appwrite::Client.new()

client
    .set_endpoint('https://[HOSTNAME_OR_IP]/v1') # Your API Endpoint
    .set_project('5df5acd0d48c2') # Your project ID
    .set_key('919c2d18fb5d4...a2ae413da83346ad2') # Your secret API key
;

database = Appwrite::Database.new(client);

response = database.delete_collection(collection_id: '[COLLECTION_ID]');

puts response


<?php

use Appwrite\Client;
use Appwrite\Services\Database;

$client = new Client();

$client
    ->setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    ->setProject('5df5acd0d48c2') // Your project ID
    ->setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

$database = new Database($client);

$result = $database->createCollection('[COLLECTION_ID]', '[NAME]', 'document', ["role:all"], ["role:all"]);


from appwrite.client import Client
from appwrite.services.health import Health

client = Client()

(client
  .set_endpoint('https://[HOSTNAME_OR_IP]/v1') # Your API Endpoint
  .set_project('5df5acd0d48c2') # Your project ID
  .set_key('919c2d18fb5d4...a2ae413da83346ad2') # Your secret API key
)

health = Health(client)

result = health.get_queue_certificates()


/** @var Appwrite\Event\Event $audits */

/** @var Appwrite\Event\Event $events */

throw new Exception('SMTP Disabled', 503, Exception::TYPE_SMTP_DISABLED);

keep keep keep keep keep replace keep keep keep keep

throw new Exception('SMTP Disabled', 503, Exception::SMTP_DISABLED);


import io.appwrite.Client
import io.appwrite.services.Account

suspend fun main() {
    val client = Client(context)
      .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
      .setProject("5df5acd0d48c2") // Your project ID
      .setJWT("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ...") // Your secret JSON Web Token

    val account = Account(client)
    val response = account.createVerification(
        url = "https://example.com"
    )
    val json = response.body?.string()
}


<?php

use Appwrite\Client;
use Appwrite\Services\Storage;

$client = new Client();

$client
    ->setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    ->setProject('5df5acd0d48c2') // Your project ID
    ->setKey('919c2d18fb5d4...a2ae413da83346ad2') // Your secret API key
;

$storage = new Storage($client);

$result = $storage->getFile('[FILE_ID]');


const sdk = new Appwrite();

sdk
    .setEndpoint('https://[HOSTNAME_OR_IP]/v1') // Your API Endpoint
    .setProject('5df5acd0d48c2') // Your project ID
;

let promise = sdk.account.delete();

promise.then(function (response) {
    console.log(response); // Success
}, function (error) {
    console.log(error); // Failure
});


const node = workflow.getNode(connection.node);

if (node && pinData && pinData[node.name]) {

/* eslint-disable @typescript-eslint/prefer-optional-chain */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-labels */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable no-continue */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
import PCancelable from 'p-cancelable';

import {
	ExecutionError,
	IConnection,
	IDataObject,
	IExecuteData,
	INode,
	INodeConnections,
	INodeExecutionData,
	IPinData,
	IRun,
	IRunData,
	IRunExecutionData,
	ISourceData,
	ITaskData,
	ITaskDataConnections,
	ITaskDataConnectionsSource,
	IWaitingForExecution,
	IWaitingForExecutionSource,
	IWorkflowExecuteAdditionalData,
	LoggerProxy as Logger,
	NodeApiError,
	NodeOperationError,
	Workflow,
	WorkflowExecuteMode,
	WorkflowOperationError,
} from 'n8n-workflow';
// eslint-disable-next-line import/no-extraneous-dependencies
import { get } from 'lodash';
// eslint-disable-next-line import/no-cycle
import { NodeExecuteFunctions } from '.';

export class WorkflowExecute {
	runExecutionData: IRunExecutionData;

	private additionalData: IWorkflowExecuteAdditionalData;

	private mode: WorkflowExecuteMode;

	constructor(
		additionalData: IWorkflowExecuteAdditionalData,
		mode: WorkflowExecuteMode,
		runExecutionData?: IRunExecutionData,
	) {
		this.additionalData = additionalData;
		this.mode = mode;
		this.runExecutionData = runExecutionData || {
			startData: {},
			resultData: {
				runData: {},
				pinData: {},
			},
			executionData: {
				contextData: {},
				nodeExecutionStack: [],
				waitingExecution: {},
				waitingExecutionSource: {},
			},
		};
	}

	/**
	 * Executes the given workflow.
	 *
	 * @param {Workflow} workflow The workflow to execute
	 * @param {INode[]} [startNodes] Node to start execution from
	 * @param {string} [destinationNode] Node to stop execution at
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	run(
		workflow: Workflow,
		startNode?: INode,
		destinationNode?: string,
		pinData?: IPinData,
	): PCancelable<IRun> {
		// Get the nodes to start workflow execution from
		startNode = startNode || workflow.getStartNode(destinationNode);

		if (startNode === undefined) {
			throw new Error('No node to start the workflow from could be found!');
		}

		// If a destination node is given we only run the direct parent nodes and no others
		let runNodeFilter: string[] | undefined;
		if (destinationNode) {
			runNodeFilter = workflow.getParentNodes(destinationNode);
			runNodeFilter.push(destinationNode);
		}

		// Initialize the data of the start nodes
		const nodeExecutionStack: IExecuteData[] = [
			{
				node: startNode,
				data: {
					main: [
						[
							{
								json: {},
							},
						],
					],
				},
				source: null,
			},
		];

		this.runExecutionData = {
			startData: {
				destinationNode,
				runNodeFilter,
			},
			resultData: {
				runData: {},
				pinData,
			},
			executionData: {
				contextData: {},
				nodeExecutionStack,
				waitingExecution: {},
				waitingExecutionSource: {},
			},
		};

		return this.processRunExecutionData(workflow);
	}

	/**
	 * Executes the given workflow but only
	 *
	 * @param {Workflow} workflow The workflow to execute
	 * @param {string[]} startNodes Nodes to start execution from
	 * @param {string} destinationNode Node to stop execution at
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	runPartialWorkflow(
		workflow: Workflow,
		runData: IRunData,
		startNodes: string[],
		destinationNode: string,
		pinData?: IPinData,
		// @ts-ignore
	): PCancelable<IRun> {
		let incomingNodeConnections: INodeConnections | undefined;
		let connection: IConnection;

		const runIndex = 0;

		// Initialize the nodeExecutionStack and waitingExecution with
		// the data from runData
		const nodeExecutionStack: IExecuteData[] = [];
		const waitingExecution: IWaitingForExecution = {};
		const waitingExecutionSource: IWaitingForExecutionSource = {};
		for (const startNode of startNodes) {
			incomingNodeConnections = workflow.connectionsByDestinationNode[startNode];

			const incomingData: INodeExecutionData[][] = [];
			let incomingSourceData: ITaskDataConnectionsSource | null = null;

			if (incomingNodeConnections === undefined) {
				// If it has no incoming data add the default empty data
				incomingData.push([
					{
						json: {},
					},
				]);
			} else {
				// Get the data of the incoming connections
				incomingSourceData = { main: [] };
				for (const connections of incomingNodeConnections.main) {
					for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
						connection = connections[inputIndex];

						if (workflow.getNode(connection.node)?.disabled) continue;

						incomingData.push(
							// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
							runData[connection.node][runIndex].data![connection.type][connection.index]!,
						);
						incomingSourceData.main.push({
							previousNode: connection.node,
						});
					}
				}
			}

			const executeData: IExecuteData = {
				node: workflow.getNode(startNode) as INode,
				data: {
					main: incomingData,
				},
				source: incomingSourceData,
			};

			nodeExecutionStack.push(executeData);

			// Check if the destinationNode has to be added as waiting
			// because some input data is already fully available
			incomingNodeConnections = workflow.connectionsByDestinationNode[destinationNode];
			if (incomingNodeConnections !== undefined) {
				for (const connections of incomingNodeConnections.main) {
					for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
						connection = connections[inputIndex];

						if (waitingExecution[destinationNode] === undefined) {
							waitingExecution[destinationNode] = {};
							waitingExecutionSource[destinationNode] = {};
						}
						if (waitingExecution[destinationNode][runIndex] === undefined) {
							waitingExecution[destinationNode][runIndex] = {};
							waitingExecutionSource[destinationNode][runIndex] = {};
						}
						if (waitingExecution[destinationNode][runIndex][connection.type] === undefined) {
							waitingExecution[destinationNode][runIndex][connection.type] = [];
							waitingExecutionSource[destinationNode][runIndex][connection.type] = [];
						}

						if (runData[connection.node] !== undefined) {
							// Input data exists so add as waiting
							// incomingDataDestination.push(runData[connection.node!][runIndex].data![connection.type][connection.index]);
							waitingExecution[destinationNode][runIndex][connection.type].push(
								runData[connection.node][runIndex].data![connection.type][connection.index],
							);
							waitingExecutionSource[destinationNode][runIndex][connection.type].push({
								previousNode: connection.node,
								previousNodeOutput: connection.index || undefined,
								previousNodeRun: runIndex || undefined,
							} as ISourceData);
						} else {
							waitingExecution[destinationNode][runIndex][connection.type].push(null);
							waitingExecutionSource[destinationNode][runIndex][connection.type].push(null);
						}
					}
				}
			}
		}

		// Only run the parent nodes and no others
		let runNodeFilter: string[] | undefined;
		// eslint-disable-next-line prefer-const
		runNodeFilter = workflow
			.getParentNodes(destinationNode)
			.filter((parentNodeName) => !workflow.getNode(parentNodeName)?.disabled);

		runNodeFilter.push(destinationNode);

		this.runExecutionData = {
			startData: {
				destinationNode,
				runNodeFilter,
			},
			resultData: {
				runData,
				pinData,
			},
			executionData: {
				contextData: {},
				nodeExecutionStack,
				waitingExecution,
				waitingExecutionSource,
			},
		};

		return this.processRunExecutionData(workflow);
	}

	/**
	 * Executes the hook with the given name
	 *
	 */
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	async executeHook(hookName: string, parameters: any[]): Promise<void> {
		// tslint:disable-line:no-any
		if (this.additionalData.hooks === undefined) {
			return;
		}

		// eslint-disable-next-line consistent-return
		return this.additionalData.hooks.executeHookFunctions(hookName, parameters);
	}

	/**
	 * Checks the incoming connection does not receive any data
	 */
	incomingConnectionIsEmpty(
		runData: IRunData,
		inputConnections: IConnection[],
		runIndex: number,
	): boolean {
		// for (const inputConnection of workflow.connectionsByDestinationNode[nodeToAdd].main[0]) {
		for (const inputConnection of inputConnections) {
			const nodeIncomingData = get(
				runData,
				`[${inputConnection.node}][${runIndex}].data.main[${inputConnection.index}]`,
			);
			if (nodeIncomingData !== undefined && (nodeIncomingData as object[]).length !== 0) {
				return false;
			}
		}
		return true;
	}

	addNodeToBeExecuted(
		workflow: Workflow,
		connectionData: IConnection,
		outputIndex: number,
		parentNodeName: string,
		nodeSuccessData: INodeExecutionData[][],
		runIndex: number,
	): void {
		let stillDataMissing = false;

		// Check if node has multiple inputs as then we have to wait for all input data
		// to be present before we can add it to the node-execution-stack
		if (workflow.connectionsByDestinationNode[connectionData.node].main.length > 1) {
			// Node has multiple inputs
			let nodeWasWaiting = true;

			if (!this.runExecutionData.executionData!.waitingExecutionSource) {
				this.runExecutionData.executionData!.waitingExecutionSource = {};
			}

			// Check if there is already data for the node
			if (
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] === undefined
			) {
				// Node does not have data yet so create a new empty one
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] = {};
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node] = {};
				nodeWasWaiting = false;
			}
			if (
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] ===
				undefined
			) {
				// Node does not have data for runIndex yet so create also empty one and init it
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] = {
					main: [],
				};
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][runIndex] =
					{
						main: [],
					};
				for (
					let i = 0;
					i < workflow.connectionsByDestinationNode[connectionData.node].main.length;
					i++
				) {
					this.runExecutionData.executionData!.waitingExecution[connectionData.node][
						runIndex
					].main.push(null);

					this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
						runIndex
					].main.push(null);
				}
			}

			// Add the new data
			if (nodeSuccessData === null) {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
					connectionData.index
				] = null;
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				].main[connectionData.index] = null;
			} else {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
					connectionData.index
				] = nodeSuccessData[outputIndex];
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				].main[connectionData.index] = {
					previousNode: parentNodeName,
					previousNodeOutput: outputIndex || undefined,
					previousNodeRun: runIndex || undefined,
				};
			}

			// Check if all data exists now
			let thisExecutionData: INodeExecutionData[] | null;
			let allDataFound = true;
			for (
				let i = 0;
				i <
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main
					.length;
				i++
			) {
				thisExecutionData =
					this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
						i
					];
				if (thisExecutionData === null) {
					allDataFound = false;
					break;
				}
			}

			if (allDataFound) {
				// All data exists for node to be executed
				// So add it to the execution stack

				const executionStackItem = {
					node: workflow.nodes[connectionData.node],
					data: this.runExecutionData.executionData!.waitingExecution[connectionData.node][
						runIndex
					],
					source:
						this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
							runIndex
						],
				} as IExecuteData;

				if (
					this.runExecutionData.executionData!.waitingExecutionSource !== null &&
					this.runExecutionData.executionData!.waitingExecutionSource !== undefined
				) {
					executionStackItem.source =
						this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
							runIndex
						];
				}

				this.runExecutionData.executionData!.nodeExecutionStack.push(executionStackItem);

				// Remove the data from waiting
				delete this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex];
				delete this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				];

				if (
					Object.keys(this.runExecutionData.executionData!.waitingExecution[connectionData.node])
						.length === 0
				) {
					// No more data left for the node so also delete that one
					delete this.runExecutionData.executionData!.waitingExecution[connectionData.node];
					delete this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node];
				}
				return;
			}
			stillDataMissing = true;

			if (!nodeWasWaiting) {
				// Get a list of all the output nodes that we can check for siblings easier
				const checkOutputNodes = [];
				// eslint-disable-next-line @typescript-eslint/no-for-in-array
				for (const outputIndexParent in workflow.connectionsBySourceNode[parentNodeName].main) {
					if (
						!workflow.connectionsBySourceNode[parentNodeName].main.hasOwnProperty(outputIndexParent)
					) {
						continue;
					}
					for (const connectionDataCheck of workflow.connectionsBySourceNode[parentNodeName].main[
						outputIndexParent
					]) {
						checkOutputNodes.push(connectionDataCheck.node);
					}
				}

				// Node was not on "waitingExecution" so it is the first time it gets
				// checked. So we have to go through all the inputs and check if they
				// are already on the list to be processed.
				// If that is not the case add it.
				for (
					let inputIndex = 0;
					inputIndex < workflow.connectionsByDestinationNode[connectionData.node].main.length;
					inputIndex++
				) {
					for (const inputData of workflow.connectionsByDestinationNode[connectionData.node].main[
						inputIndex
					]) {
						if (inputData.node === parentNodeName) {
							// Is the node we come from so its data will be available for sure
							continue;
						}

						const executionStackNodes = this.runExecutionData.executionData!.nodeExecutionStack.map(
							(stackData) => stackData.node.name,
						);

						// Check if that node is also an output connection of the
						// previously processed one
						if (inputData.node !== parentNodeName && checkOutputNodes.includes(inputData.node)) {
							// So the parent node will be added anyway which
							// will then process this node next. So nothing to do
							// unless the incoming data of the node is empty
							// because then it would not be executed
							if (
								!this.incomingConnectionIsEmpty(
									this.runExecutionData.resultData.runData,
									workflow.connectionsByDestinationNode[inputData.node].main[0],
									runIndex,
								)
							) {
								continue;
							}
						}

						// Check if it is already in the execution stack
						if (executionStackNodes.includes(inputData.node)) {
							// Node is already on the list to be executed
							// so there is nothing to do
							continue;
						}

						// Check if node got processed already
						if (this.runExecutionData.resultData.runData[inputData.node] !== undefined) {
							// Node got processed already so no need to add it
							continue;
						}

						// Check if any of the parent nodes does not have any inputs. That
						// would mean that it has to get added to the list of nodes to process.
						const parentNodes = workflow.getParentNodes(inputData.node, 'main', -1);
						let nodeToAdd: string | undefined = inputData.node;
						parentNodes.push(inputData.node);
						parentNodes.reverse();

						for (const parentNode of parentNodes) {
							// Check if that node is also an output connection of the
							// previously processed one
							if (inputData.node !== parentNode && checkOutputNodes.includes(parentNode)) {
								// So the parent node will be added anyway which
								// will then process this node next. So nothing to do.
								nodeToAdd = undefined;
								break;
							}

							// Check if it is already in the execution stack
							if (executionStackNodes.includes(parentNode)) {
								// Node is already on the list to be executed
								// so there is nothing to do
								nodeToAdd = undefined;
								break;
							}

							// Check if node got processed already
							if (this.runExecutionData.resultData.runData[parentNode] !== undefined) {
								// Node got processed already so we can use the
								// output data as input of this node
								break;
							}

							nodeToAdd = parentNode;
						}
						const parentNodesNodeToAdd = workflow.getParentNodes(nodeToAdd as string);
						if (
							parentNodesNodeToAdd.includes(parentNodeName) &&
							nodeSuccessData[outputIndex].length === 0
						) {
							// We do not add the node if there is no input data and the node that should be connected
							// is a child of the parent node. Because else it would run a node even though it should be
							// specifically not run, as it did not receive any data.
							nodeToAdd = undefined;
						}

						if (nodeToAdd === undefined) {
							// No node has to get added so process
							continue;
						}

						let addEmptyItem = false;

						if (workflow.connectionsByDestinationNode[nodeToAdd] === undefined) {
							// Add empty item if the node does not have any input connections
							addEmptyItem = true;
						} else if (
							this.incomingConnectionIsEmpty(
								this.runExecutionData.resultData.runData,
								workflow.connectionsByDestinationNode[nodeToAdd].main[0],
								runIndex,
							)
						) {
							// Add empty item also if the input data is empty
							addEmptyItem = true;
						}

						if (addEmptyItem) {
							// Add only node if it does not have any inputs because else it will
							// be added by its input node later anyway.
							this.runExecutionData.executionData!.nodeExecutionStack.push({
								node: workflow.getNode(nodeToAdd) as INode,
								data: {
									main: [
										[
											{
												json: {},
											},
										],
									],
								},
								source: {
									main: [
										{
											previousNode: parentNodeName,
											previousNodeOutput: outputIndex || undefined,
											previousNodeRun: runIndex || undefined,
										},
									],
								},
							});
						}
					}
				}
			}
		}

		// Make sure the array has all the values
		const connectionDataArray: Array<INodeExecutionData[] | null> = [];
		for (let i: number = connectionData.index; i >= 0; i--) {
			connectionDataArray[i] = null;
		}

		// Add the data of the current execution
		if (nodeSuccessData === null) {
			connectionDataArray[connectionData.index] = null;
		} else {
			connectionDataArray[connectionData.index] = nodeSuccessData[outputIndex];
		}

		if (stillDataMissing) {
			// Additional data is needed to run node so add it to waiting
			if (
				!this.runExecutionData.executionData!.waitingExecution.hasOwnProperty(connectionData.node)
			) {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] = {};
			}
			this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] = {
				main: connectionDataArray,
			};
		} else {
			// All data is there so add it directly to stack
			this.runExecutionData.executionData!.nodeExecutionStack.push({
				node: workflow.nodes[connectionData.node],
				data: {
					main: connectionDataArray,
				},
				source: {
					main: [
						{
							previousNode: parentNodeName,
							previousNodeOutput: outputIndex || undefined,
							previousNodeRun: runIndex || undefined,
						},
					],
				},
			});
		}
	}

	/**
	 * Runs the given execution data.
	 *
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	processRunExecutionData(workflow: Workflow): PCancelable<IRun> {
		Logger.verbose('Workflow execution started', { workflowId: workflow.id });

		const startedAt = new Date();

		const startNode = this.runExecutionData.executionData!.nodeExecutionStack[0].node.name;

		let destinationNode: string | undefined;
		if (this.runExecutionData.startData && this.runExecutionData.startData.destinationNode) {
			destinationNode = this.runExecutionData.startData.destinationNode;
		}

		const pinDataNodeNames = Object.keys(this.runExecutionData.resultData.pinData ?? {});

		const workflowIssues = workflow.checkReadyForExecution({
			startNode,
			destinationNode,
			pinDataNodeNames,
		});
		if (workflowIssues !== null) {
			throw new Error(
				'The workflow has issues and can for that reason not be executed. Please fix them first.',
			);
		}

		// Variables which hold temporary data for each node-execution
		let executionData: IExecuteData;
		let executionError: ExecutionError | undefined;
		let executionNode: INode;
		let nodeSuccessData: INodeExecutionData[][] | null | undefined;
		let runIndex: number;
		let startTime: number;
		let taskData: ITaskData;

		if (this.runExecutionData.startData === undefined) {
			this.runExecutionData.startData = {};
		}

		if (this.runExecutionData.waitTill) {
			const lastNodeExecuted = this.runExecutionData.resultData.lastNodeExecuted as string;
			this.runExecutionData.executionData!.nodeExecutionStack[0].node.disabled = true;
			this.runExecutionData.waitTill = undefined;
			this.runExecutionData.resultData.runData[lastNodeExecuted].pop();
		}

		let currentExecutionTry = '';
		let lastExecutionTry = '';
		let closeFunction: Promise<void> | undefined;

		return new PCancelable(async (resolve, reject, onCancel) => {
			let gotCancel = false;

			onCancel.shouldReject = false;
			onCancel(() => {
				gotCancel = true;
			});

			const returnPromise = (async () => {
				try {
					await this.executeHook('workflowExecuteBefore', [workflow]);
				} catch (error) {
					// Set the error that it can be saved correctly
					executionError = {
						...(error as NodeOperationError | NodeApiError),
						message: (error as NodeOperationError | NodeApiError).message,
						stack: (error as NodeOperationError | NodeApiError).stack,
					};

					// Set the incoming data of the node that it can be saved correctly
					// eslint-disable-next-line prefer-destructuring
					executionData = this.runExecutionData.executionData!.nodeExecutionStack[0];
					this.runExecutionData.resultData = {
						runData: {
							[executionData.node.name]: [
								{
									startTime,
									executionTime: new Date().getTime() - startTime,
									data: {
										main: executionData.data.main,
									} as ITaskDataConnections,
									source: [],
								},
							],
						},
						lastNodeExecuted: executionData.node.name,
						error: executionError,
					};

					throw error;
				}

				executionLoop: while (
					this.runExecutionData.executionData!.nodeExecutionStack.length !== 0
				) {
					if (
						this.additionalData.executionTimeoutTimestamp !== undefined &&
						Date.now() >= this.additionalData.executionTimeoutTimestamp
					) {
						gotCancel = true;
					}

					// @ts-ignore
					if (gotCancel) {
						return Promise.resolve();
					}

					nodeSuccessData = null;
					executionError = undefined;
					executionData =
						this.runExecutionData.executionData!.nodeExecutionStack.shift() as IExecuteData;
					executionNode = executionData.node;

					// Update the pairedItem information on items
					const newTaskDataConnections: ITaskDataConnections = {};
					for (const inputName of Object.keys(executionData.data)) {
						newTaskDataConnections[inputName] = executionData.data[inputName].map(
							(input, inputIndex) => {
								if (input === null) {
									return input;
								}

								return input.map((item, itemIndex) => {
									return {
										...item,
										pairedItem: {
											item: itemIndex,
											input: inputIndex || undefined,
										},
									};
								});
							},
						);
					}
					executionData.data = newTaskDataConnections;

					Logger.debug(`Start processing node "${executionNode.name}"`, {
						node: executionNode.name,
						workflowId: workflow.id,
					});
					await this.executeHook('nodeExecuteBefore', [executionNode.name]);

					// Get the index of the current run
					runIndex = 0;
					if (this.runExecutionData.resultData.runData.hasOwnProperty(executionNode.name)) {
						runIndex = this.runExecutionData.resultData.runData[executionNode.name].length;
					}

					currentExecutionTry = `${executionNode.name}:${runIndex}`;

					if (currentExecutionTry === lastExecutionTry) {
						throw new Error('Did stop execution because execution seems to be in endless loop.');
					}

					if (
						this.runExecutionData.startData!.runNodeFilter !== undefined &&
						this.runExecutionData.startData!.runNodeFilter.indexOf(executionNode.name) === -1
					) {
						// If filter is set and node is not on filter skip it, that avoids the problem that it executes
						// leafs that are parallel to a selected destinationNode. Normally it would execute them because
						// they have the same parent and it executes all child nodes.
						continue;
					}

					// Check if all the data which is needed to run the node is available
					if (workflow.connectionsByDestinationNode.hasOwnProperty(executionNode.name)) {
						// Check if the node has incoming connections
						if (workflow.connectionsByDestinationNode[executionNode.name].hasOwnProperty('main')) {
							let inputConnections: IConnection[][];
							let connectionIndex: number;

							// eslint-disable-next-line prefer-const
							inputConnections = workflow.connectionsByDestinationNode[executionNode.name].main;

							for (
								connectionIndex = 0;
								connectionIndex < inputConnections.length;
								connectionIndex++
							) {
								if (
									workflow.getHighestNode(executionNode.name, 'main', connectionIndex).length === 0
								) {
									// If there is no valid incoming node (if all are disabled)
									// then ignore that it has inputs and simply execute it as it is without
									// any data
									continue;
								}

								if (!executionData.data.hasOwnProperty('main')) {
									// ExecutionData does not even have the connection set up so can
									// not have that data, so add it again to be executed later
									this.runExecutionData.executionData!.nodeExecutionStack.push(executionData);
									lastExecutionTry = currentExecutionTry;
									continue executionLoop;
								}

								// Check if it has the data for all the inputs
								// The most nodes just have one but merge node for example has two and data
								// of both inputs has to be available to be able to process the node.
								if (
									executionData.data.main!.length < connectionIndex ||
									executionData.data.main![connectionIndex] === null
								) {
									// Does not have the data of the connections so add back to stack
									this.runExecutionData.executionData!.nodeExecutionStack.push(executionData);
									lastExecutionTry = currentExecutionTry;
									continue executionLoop;
								}
							}
						}
					}

					startTime = new Date().getTime();

					let maxTries = 1;
					if (executionData.node.retryOnFail === true) {
						// TODO: Remove the hardcoded default-values here and also in NodeSettings.vue
						maxTries = Math.min(5, Math.max(2, executionData.node.maxTries || 3));
					}

					let waitBetweenTries = 0;
					if (executionData.node.retryOnFail === true) {
						// TODO: Remove the hardcoded default-values here and also in NodeSettings.vue
						waitBetweenTries = Math.min(
							5000,
							Math.max(0, executionData.node.waitBetweenTries || 1000),
						);
					}

					for (let tryIndex = 0; tryIndex < maxTries; tryIndex++) {
						// @ts-ignore
						if (gotCancel) {
							return Promise.resolve();
						}
						try {
							if (tryIndex !== 0) {
								// Reset executionError from previous error try
								executionError = undefined;
								if (waitBetweenTries !== 0) {
									// TODO: Improve that in the future and check if other nodes can
									//       be executed in the meantime
									// eslint-disable-next-line @typescript-eslint/no-shadow
									await new Promise((resolve) => {
										setTimeout(() => {
											resolve(undefined);
										}, waitBetweenTries);
									});
								}
							}

							const { pinData } = this.runExecutionData.resultData;

							if (pinData && !executionNode.disabled && pinData[executionNode.name] !== undefined) {
								const nodePinData = pinData[executionNode.name];

								nodeSuccessData = [nodePinData]; // always zeroth runIndex
							} else {
								Logger.debug(`Running node "${executionNode.name}" started`, {
									node: executionNode.name,
									workflowId: workflow.id,
								});
								const runNodeData = await workflow.runNode(
									executionData,
									this.runExecutionData,
									runIndex,
									this.additionalData,
									NodeExecuteFunctions,
									this.mode,
								);
								nodeSuccessData = runNodeData.data;

								if (runNodeData.closeFunction) {
									// Explanation why we do this can be found in n8n-workflow/Workflow.ts -> runNode
									// eslint-disable-next-line @typescript-eslint/no-unsafe-call
									closeFunction = runNodeData.closeFunction();
								}
							}

							Logger.debug(`Running node "${executionNode.name}" finished successfully`, {
								node: executionNode.name,
								workflowId: workflow.id,
							});

							if (nodeSuccessData) {
								// Check if the output data contains pairedItem data
								checkOutputData: for (const outputData of nodeSuccessData) {
									if (outputData === null) {
										continue;
									}
									for (const [index, item] of outputData.entries()) {
										if (!item.pairedItem) {
											// The pairedItem data is missing, so check if it can get automatically fixed
											if (
												executionData.data.main.length === 1 &&
												executionData.data.main[0]?.length === 1
											) {
												// The node has one input and one incoming item, so we know
												// that all items must originate from that single
												item.pairedItem = {
													item: 0,
												};
											} else if (
												nodeSuccessData.length === 1 &&
												executionData.data.main.length === 1 &&
												executionData.data.main[0]?.length === nodeSuccessData[0].length
											) {
												// The node has one input and one output. The number of items on both is
												// identical so we can make the reasonable assumption that each of the input
												// items is the origin of the corresponding output items
												item.pairedItem = {
													item: index,
												};
											} else {
												// In all other cases autofixing is not possible
												break checkOutputData;
											}
										}
									}
								}
							}

							if (nodeSuccessData === undefined) {
								// Node did not get executed
								nodeSuccessData = null;
							} else {
								this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name;
							}

							if (nodeSuccessData === null || nodeSuccessData[0][0] === undefined) {
								if (executionData.node.alwaysOutputData === true) {
									nodeSuccessData = nodeSuccessData || [];
									nodeSuccessData[0] = [
										{
											json: {},
										},
									];
								}
							}

							if (nodeSuccessData === null && !this.runExecutionData.waitTill!) {
								// If null gets returned it means that the node did succeed
								// but did not have any data. So the branch should end
								// (meaning the nodes afterwards should not be processed)
								continue executionLoop;
							}

							break;
						} catch (error) {
							this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name;

							executionError = {
								...(error as NodeOperationError | NodeApiError),
								message: (error as NodeOperationError | NodeApiError).message,
								stack: (error as NodeOperationError | NodeApiError).stack,
							};

							Logger.debug(`Running node "${executionNode.name}" finished with error`, {
								node: executionNode.name,
								workflowId: workflow.id,
							});
						}
					}

					// Add the data to return to the user
					// (currently does not get cloned as data does not get changed, maybe later we should do that?!?!)

					if (!this.runExecutionData.resultData.runData.hasOwnProperty(executionNode.name)) {
						this.runExecutionData.resultData.runData[executionNode.name] = [];
					}

					taskData = {
						startTime,
						executionTime: new Date().getTime() - startTime,
						source: !executionData.source ? [] : executionData.source.main,
					};

					if (executionError !== undefined) {
						taskData.error = executionError;

						if (executionData.node.continueOnFail === true) {
							// Workflow should continue running even if node errors
							if (executionData.data.hasOwnProperty('main') && executionData.data.main.length > 0) {
								// Simply get the input data of the node if it has any and pass it through
								// to the next node
								if (executionData.data.main[0] !== null) {
									nodeSuccessData = [executionData.data.main[0]];
								}
							}
						} else {
							// Node execution did fail so add error and stop execution
							this.runExecutionData.resultData.runData[executionNode.name].push(taskData);

							// Add the execution data again so that it can get restarted
							this.runExecutionData.executionData!.nodeExecutionStack.unshift(executionData);

							await this.executeHook('nodeExecuteAfter', [
								executionNode.name,
								taskData,
								this.runExecutionData,
							]);

							break;
						}
					}

					// Merge error information to default output for now
					// As the new nodes can report the errors in
					// the `error` property.
					for (const execution of nodeSuccessData!) {
						for (const lineResult of execution) {
							if (
								lineResult.json !== undefined &&
								lineResult.json.$error !== undefined &&
								lineResult.json.$json !== undefined
							) {
								lineResult.error = lineResult.json.$error as NodeApiError | NodeOperationError;
								lineResult.json = {
									error: (lineResult.json.$error as NodeApiError | NodeOperationError).message,
								};
							} else if (lineResult.error !== undefined) {
								lineResult.json = { error: lineResult.error.message };
							}
						}
					}

					// Node executed successfully. So add data and go on.
					taskData.data = {
						main: nodeSuccessData,
					} as ITaskDataConnections;

					this.runExecutionData.resultData.runData[executionNode.name].push(taskData);

					if (this.runExecutionData.waitTill!) {
						await this.executeHook('nodeExecuteAfter', [
							executionNode.name,
							taskData,
							this.runExecutionData,
						]);

						// Add the node back to the stack that the workflow can start to execute again from that node
						this.runExecutionData.executionData!.nodeExecutionStack.unshift(executionData);

						break;
					}

					if (
						this.runExecutionData.startData &&
						this.runExecutionData.startData.destinationNode &&
						this.runExecutionData.startData.destinationNode === executionNode.name
					) {
						// Before stopping, make sure we are executing hooks so
						// That frontend is notified for example for manual executions.
						await this.executeHook('nodeExecuteAfter', [
							executionNode.name,
							taskData,
							this.runExecutionData,
						]);

						// If destination node is defined and got executed stop execution
						continue;
					}

					// Add the nodes to which the current node has an output connection to that they can
					// be executed next
					if (workflow.connectionsBySourceNode.hasOwnProperty(executionNode.name)) {
						if (workflow.connectionsBySourceNode[executionNode.name].hasOwnProperty('main')) {
							let outputIndex: string;
							let connectionData: IConnection;
							// Iterate over all the outputs

							// Add the nodes to be executed
							// eslint-disable-next-line @typescript-eslint/no-for-in-array
							for (outputIndex in workflow.connectionsBySourceNode[executionNode.name].main) {
								if (
									!workflow.connectionsBySourceNode[executionNode.name].main.hasOwnProperty(
										outputIndex,
									)
								) {
									continue;
								}

								// Iterate over all the different connections of this output
								for (connectionData of workflow.connectionsBySourceNode[executionNode.name].main[
									outputIndex
								]) {
									if (!workflow.nodes.hasOwnProperty(connectionData.node)) {
										return Promise.reject(
											new Error(
												`The node "${executionNode.name}" connects to not found node "${connectionData.node}"`,
											),
										);
									}

									if (
										nodeSuccessData![outputIndex] &&
										(nodeSuccessData![outputIndex].length !== 0 || connectionData.index > 0)
									) {
										// Add the node only if it did execute or if connected to second "optional" input
										this.addNodeToBeExecuted(
											workflow,
											connectionData,
											parseInt(outputIndex, 10),
											executionNode.name,
											nodeSuccessData!,
											runIndex,
										);
									}
								}
							}
						}
					}

					// If we got here, it means that we did not stop executing from manual executions / destination.
					// Execute hooks now to make sure that all hooks are executed properly
					// Await is needed to make sure that we don't fall into concurrency problems
					// When saving node execution data
					await this.executeHook('nodeExecuteAfter', [
						executionNode.name,
						taskData,
						this.runExecutionData,
					]);
				}

				return Promise.resolve();
			})()
				.then(async () => {
					if (gotCancel && executionError === undefined) {
						return this.processSuccessExecution(
							startedAt,
							workflow,
							new WorkflowOperationError('Workflow has been canceled or timed out!'),
							closeFunction,
						);
					}
					return this.processSuccessExecution(startedAt, workflow, executionError, closeFunction);
				})
				.catch(async (error) => {
					const fullRunData = this.getFullRunData(startedAt);

					fullRunData.data.resultData.error = {
						...error,
						message: error.message,
						stack: error.stack,
					};

					// Check if static data changed
					let newStaticData: IDataObject | undefined;
					// eslint-disable-next-line no-underscore-dangle
					if (workflow.staticData.__dataChanged === true) {
						// Static data of workflow changed
						newStaticData = workflow.staticData;
					}
					await this.executeHook('workflowExecuteAfter', [fullRunData, newStaticData]).catch(
						// eslint-disable-next-line @typescript-eslint/no-shadow
						(error) => {
							// eslint-disable-next-line no-console
							console.error('There was a problem running hook "workflowExecuteAfter"', error);
						},
					);

					if (closeFunction) {
						try {
							await closeFunction;
						} catch (errorClose) {
							Logger.error(
								// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions
								`There was a problem deactivating trigger of workflow "${workflow.id}": "${errorClose.message}"`,
								{
									workflowId: workflow.id,
								},
							);
						}
					}

					return fullRunData;
				});

			return returnPromise.then(resolve);
		});
	}

	async processSuccessExecution(
		startedAt: Date,
		workflow: Workflow,
		executionError?: ExecutionError,
		closeFunction?: Promise<void>,
	): Promise<IRun> {
		const fullRunData = this.getFullRunData(startedAt);

		if (executionError !== undefined) {
			Logger.verbose(`Workflow execution finished with error`, {
				error: executionError,
				workflowId: workflow.id,
			});
			fullRunData.data.resultData.error = {
				...executionError,
				message: executionError.message,
				stack: executionError.stack,
			} as ExecutionError;
		} else if (this.runExecutionData.waitTill!) {
			// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
			Logger.verbose(`Workflow execution will wait until ${this.runExecutionData.waitTill}`, {
				workflowId: workflow.id,
			});
			fullRunData.waitTill = this.runExecutionData.waitTill;
		} else {
			Logger.verbose(`Workflow execution finished successfully`, { workflowId: workflow.id });
			fullRunData.finished = true;
		}

		// Check if static data changed
		let newStaticData: IDataObject | undefined;
		// eslint-disable-next-line no-underscore-dangle
		if (workflow.staticData.__dataChanged === true) {
			// Static data of workflow changed
			newStaticData = workflow.staticData;
		}

		await this.executeHook('workflowExecuteAfter', [fullRunData, newStaticData]);

		if (closeFunction) {
			try {
				await closeFunction;
			} catch (error) {
				Logger.error(
					// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
					`There was a problem deactivating trigger of workflow "${workflow.id}": "${error.message}"`,
					{
						workflowId: workflow.id,
					},
				);
			}
		}

		return fullRunData;
	}

	getFullRunData(startedAt: Date): IRun {
		const fullRunData: IRun = {
			data: this.runExecutionData,
			mode: this.mode,
			startedAt,
			stoppedAt: new Date(),
		};

		return fullRunData;
	}
}


@use "mixins/mixins";
@use "./common/var";

@include mixins.b(textarea) {
	position: relative;
	display: inline-block;
	width: 100%;
	vertical-align: bottom;
	font-size: var.$font-size-base;

	@include mixins.e(inner) {
		display: block;
		resize: vertical;
		padding: 8px 12px 5px 12px;
		line-height: 1.5;
		box-sizing: border-box;
		width: 100%;
		font-size: inherit;
		color: var.$input-font-color;
		background-color: var.$input-background-color;
		background-image: none;
		border-radius: var.$input-border-radius;
		transition: var.$border-transition-base;

		&,
		&:hover {
			border: var.$input-border;
		}

		&::placeholder {
			color: var.$input-placeholder-color;
		}

		&:focus {
			outline: none;
			border-color: var.$input-focus-border;
		}
	}

	& .el-input__count {
		color: var(--color-info);
		background: var.$color-white;
		position: absolute;
		font-size: 12px;
		bottom: 5px;
		right: 10px;
	}

	@include mixins.when(disabled) {
		.el-textarea__inner {
			background-color: var.$input-disabled-fill;
			border-color: var.$input-disabled-border;
			color: var.$input-disabled-color;
			cursor: not-allowed;

			&::placeholder {
				color: var.$input-disabled-placeholder-color;
			}
		}
	}

	@include mixins.when(exceed) {
		.el-textarea__inner {
			border-color: var(--color-danger);
		}

		.el-input__count {
			color: var(--color-danger);
		}
	}
}

@include mixins.b(input) {
	position: relative;
	font-size: var.$input-font-size;
	display: inline-block;
	width: 100%;
	@include mixins.scroll-bar;

	& .el-input__clear {
		color: var.$input-clear-color;
		font-size: var.$input-font-size;
		cursor: pointer;
		transition: var.$color-transition-base;

		&:hover {
			color: var.$input-clear-hover-color;
		}
	}

	& .el-input__count {
		height: 100%;
		display: inline-flex;
		align-items: center;
		color: var(--color-info);
		font-size: 12px;

		.el-input__count-inner {
			background: var.$color-white;
			line-height: initial;
			display: inline-block;
			padding: 0 5px;
		}
	}

	@include mixins.e(inner) {
		-webkit-appearance: none;
		background-color: var.$input-background-color;
		background-image: none;
		border-radius: var.$input-border-radius;
		border: var.$input-border;
		box-sizing: border-box;
		color: var.$input-font-color;
		display: inline-block;
		font-size: inherit;
		height: var.$input-height;
		line-height: var.$input-height;
		outline: none;
		padding: 0 0 0 var(--spacing-2xs);
		transition: var.$border-transition-base;
		width: 100%;

		&::placeholder {
			color: var.$input-placeholder-color;
		}

		&:focus {
			outline: none;
			border-color: var.$input-focus-border;
		}
	}

	@include mixins.e(suffix) {
		position: absolute;
		height: 100%;
		right: var(--spacing-2xs);
		top: 0;
		text-align: center;
		color: var(--color-text-light);
		transition: all 0.3s;
		pointer-events: none;
		display: flex;
		align-items: center;
	}

	@include mixins.e(suffix-inner) {
		pointer-events: all;
	}

	@include mixins.e(prefix) {
		position: absolute;
		height: 100%;
		left: 14px;
		top: 0;
		text-align: center;
		color: var.$input-icon-color;
		transition: all 0.3s;
		display: flex;
		align-items: center;
	}

	@include mixins.e(icon) {
		height: 100%;
		text-align: center;
		transition: all 0.3s;
		line-height: var.$input-height;

		&:after {
			content: '';
			height: 100%;
			width: 0;
			display: inline-block;
			vertical-align: middle;
		}
	}

	@include mixins.e(validateIcon) {
		pointer-events: none;
	}

	@include mixins.when(active) {
		.el-input__inner {
			outline: none;
			border-color: var.$input-focus-border;
		}
	}

	@include mixins.when(disabled) {
		.el-input__inner {
			background-color: var.$input-disabled-fill;
			border-color: var.$input-disabled-border;
			color: var.$input-disabled-color;
			cursor: not-allowed;

			&::placeholder {
				color: var.$input-disabled-placeholder-color;
			}
		}

		.el-input__icon {
			cursor: not-allowed;
		}
	}

	@include mixins.when(exceed) {
		.el-input__inner {
			border-color: var(--color-danger);
		}

		.el-input__suffix {
			.el-input__count {
				color: var(--color-danger);
			}
		}
	}

	@include mixins.m(suffix) {
		.el-input__inner {
			padding-right: 30px;
		}
	}

	@include mixins.m(prefix) {
		.el-input__inner {
			padding-left: 37px;
		}
	}

	@include mixins.m(medium) {
		font-size: var.$input-medium-font-size;

		@include mixins.e(inner) {
			height: var.$input-medium-height;
			line-height: var.$input-medium-height;
		}

		.el-input__icon {
			line-height: var.$input-medium-height;
		}
	}
	@include mixins.m(small) {
		font-size: var.$input-small-font-size;

		@include mixins.e(inner) {
			height: var.$input-small-height;
			line-height: var.$input-small-height;
		}

		.el-input__icon {
			line-height: var.$input-small-height;
		}
	}
	@include mixins.m(mini) {
		font-size: var.$input-mini-font-size;

		@include mixins.e(inner) {
			height: var.$input-mini-height;
			line-height: var.$input-mini-height;
		}

		.el-input__icon {
			line-height: var.$input-mini-height;
		}
	}
}

@include mixins.b(input-group) {
	line-height: normal;
	display: inline-table;
	width: 100%;
	border-collapse: separate;
	border-spacing: 0;

	> .el-input__inner {
		vertical-align: middle;
		display: table-cell;
	}

	@include mixins.e((append, prepend)) {
		background-color: var.$background-color-base;
		color: var(--color-info);
		vertical-align: middle;
		display: table-cell;
		position: relative;
		border: var(--border-base);
		border-radius: var.$input-border-radius;
		padding: 0 10px;
		width: 1px;
		white-space: nowrap;
		font-weight: var(--font-weight-regular);

		&:focus {
			outline: none;
		}

		.el-select,
		.el-button {
			display: inline-block;
			margin: -10px -20px;
		}

		button.el-button,
		div.el-select .el-input__inner,
		div.el-select:hover .el-input__inner {
			border-color: transparent;
			background-color: transparent;
			color: inherit;
			border-top: 0;
			border-bottom: 0;
		}

		.el-button,
		.el-input {
			font-size: inherit;
		}
	}

	@include mixins.e(prepend) {
		border-right: 0;
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
	}

	@include mixins.e(append) {
		border-left: 0;
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
	}

	@include mixins.m(prepend) {
		.el-input__inner {
			border-top-left-radius: 0;
			border-bottom-left-radius: 0;
		}
		.el-select .el-input.is-focus .el-input__inner {
			border-color: transparent;
		}
	}

	@include mixins.m(append) {
		.el-input__inner {
			border-top-right-radius: 0;
			border-bottom-right-radius: 0;
		}
		.el-select .el-input.is-focus .el-input__inner {
			border-color: transparent;
		}
	}
}

/** disalbe default clear on IE */
.el-input__inner::-ms-clear {
	display: none;
	width: 0;
	height: 0;
}


export const indexSettings = `{
  "settings": {
    "index": {
      "number_of_shards": 3,
      "number_of_replicas": 2
    }
  }
}`;

export const mappings = `{
  "mappings": {
    "properties": {
      "field1": { "type": "text" }
    }
  }
}`;

export const aliases = `{
  "aliases": {
    "alias_1": {},
    "alias_2": {
      "filter": {
        "term": { "user.id": "kimchy" }
      },
      "routing": "shard-1"
    }
  }
}`;

export const query = `{
  "query": {
    "term": {
      "user.id": "john"
    }
  }
}`;

export const document = `{
  "timestamp": "2099-05-06T16:21:15.000Z",
  "event": {
    "original": "192.0.2.42 - - [06/May/2099:16:21:15 +0000] \"GET /images/bg.jpg HTTP/1.0\" 200 24736"
  }
}`;


keep replace replace replace replace keep keep keep


import { INodeProperties } from 'n8n-workflow';

const resource = ['invoice'];

export const invoiceOperations: INodeProperties[] = [
	{
		displayName: 'Operation',
		name: 'operation',
		type: 'options',
		noDataExpression: true,
		displayOptions: {
			show: {
				resource,
			},
		},
		options: [
			{
				name: 'Create',
				value: 'create',
				description: 'Create an invoice',
				action: 'Create an invoice',
			},
			{
				name: 'Delete',
				value: 'delete',
				description: 'Delete an invoice',
				action: 'Delete an invoice',
			},
			{
				name: 'Get',
				value: 'get',
				description: 'Get data of an invoice',
				action: 'Get data of an invoice',
			},
			{
				name: 'Get Many',
				value: 'getAll',
				description: 'Get data of many invoices',
				action: 'Get data of all invoices',
			},
			{
				name: 'Update',
				value: 'update',
				description: 'Update an invoice',
				action: 'Update an invoice',
			},
		],
		default: 'getAll',
	},
];

export const invoiceFields: INodeProperties[] = [
	/* -------------------------------------------------------------------------- */
	/*                                invoice:getAll                              */
	/* -------------------------------------------------------------------------- */

	{
		displayName: 'Return All',
		name: 'returnAll',
		type: 'boolean',
		displayOptions: {
			show: {
				resource,
				operation: ['getAll'],
			},
		},
		default: false,
		description: 'Whether to return all results or only up to a given limit',
	},
	{
		displayName: 'Limit',
		name: 'limit',
		type: 'number',
		displayOptions: {
			show: {
				resource,
				operation: ['getAll'],
				returnAll: [false],
			},
		},
		typeOptions: {
			minValue: 1,
			maxValue: 100,
		},
		default: 100,
		description: 'Max number of results to return',
	},
	{
		displayName: 'Filters',
		name: 'filters',
		type: 'collection',
		placeholder: 'Add Filter',
		default: {},
		displayOptions: {
			show: {
				resource,
				operation: ['getAll'],
			},
		},
		options: [
			{
				displayName: 'Client ID',
				name: 'client_id',
				type: 'string',
				default: '',
				description: 'Only return time entries belonging to the client with the given ID',
			},
			{
				displayName: 'From',
				name: 'from',
				type: 'dateTime',
				default: '',
				description: 'Only return time entries with a spent_date on or after the given date',
			},
			{
				displayName: 'Page',
				name: 'page',
				type: 'number',
				typeOptions: {
					minValue: 1,
				},
				default: 1,
				description:
					'The page number to use in pagination. For instance, if you make a list request and receive 100 records, your subsequent call can include page=2 to retrieve the next page of the list. (Default: 1)',
			},
			{
				displayName: 'Project ID',
				name: 'project_id',
				type: 'string',
				default: '',
				description: 'Only return time entries belonging to the client with the given ID',
			},
			{
				displayName: 'State',
				name: 'state',
				type: 'multiOptions',
				options: [
					{
						name: 'Draft',
						value: 'draft',
					},
					{
						name: 'Open',
						value: 'open',
					},
					{
						name: 'Paid',
						value: 'paid',
					},
					{
						name: 'Closed',
						value: 'closed',
					},
				],
				default: [],
				description:
					'Only return invoices with a state matching the value provided. Options: draft, open, paid, or closed.',
			},
			{
				displayName: 'To',
				name: 'to',
				type: 'dateTime',
				default: '',
				description: 'Only return time entries with a spent_date on or before the given date',
			},

			{
				displayName: 'Updated Since',
				name: 'updated_since',
				type: 'dateTime',
				default: '',
				description:
					'Only return time entries that have been updated since the given date and time',
			},
		],
	},

	/* -------------------------------------------------------------------------- */
	/*                                invoice:get                                 */
	/* -------------------------------------------------------------------------- */
	{
		displayName: 'Invoice ID',
		name: 'id',
		type: 'string',
		default: '',
		required: true,
		displayOptions: {
			show: {
				operation: ['get'],
				resource,
			},
		},
		description: 'The ID of the invoice you are retrieving',
	},

	/* -------------------------------------------------------------------------- */
	/*                                invoice:delete                              */
	/* -------------------------------------------------------------------------- */
	{
		displayName: 'Invoice ID',
		name: 'id',
		type: 'string',
		default: '',
		required: true,
		displayOptions: {
			show: {
				operation: ['delete'],
				resource,
			},
		},
		description: 'The ID of the invoice want to delete',
	},

	/* -------------------------------------------------------------------------- */
	/*                                invoice:create                              */
	/* -------------------------------------------------------------------------- */
	{
		displayName: 'Client ID',
		name: 'clientId',
		type: 'string',
		displayOptions: {
			show: {
				operation: ['create'],
				resource,
			},
		},
		default: '',
		required: true,
		description: 'The ID of the retainer associated with this invoice',
	},
	{
		displayName: 'Additional Fields',
		name: 'additionalFields',
		type: 'collection',
		placeholder: 'Add Field',
		displayOptions: {
			show: {
				operation: ['create'],
				resource,
			},
		},
		default: {},
		options: [
			{
				displayName: 'Currency',
				name: 'currency',
				type: 'string',
				default: '',
				description:
					'The currency used by the invoice. If not provided, the client’s currency will be used. See a list of supported currencies',
			},
			{
				displayName: 'Discount',
				name: 'over_budget_notification_percentage',
				type: 'string',
				default: '',
				description:
					'This percentage is subtracted from the subtotal. Example: use 10.0 for 10.0%.',
			},
			{
				displayName: 'Due Date',
				name: 'ends_on',
				type: 'dateTime',
				default: '',
				description:
					'Date the invoice is due. Defaults to the issue_date if no payment_term is specified.',
			},
			{
				displayName: 'Estimate ID',
				name: 'estimate_id',
				type: 'string',
				default: '',
				description: 'The ID of the estimate associated with this invoice',
			},
			{
				displayName: 'Issue Date',
				name: 'issue_date',
				type: 'dateTime',
				default: '',
				description: 'Date the invoice was issued. Defaults to today’s date.',
			},
			{
				displayName: 'Notes',
				name: 'notes',
				type: 'string',
				default: '',
				description: 'Notes about the project',
			},
			{
				displayName: 'Number',
				name: 'number',
				type: 'string',
				default: '',
				description: 'If no value is set, the number will be automatically generated',
			},
			{
				displayName: 'Payment Term',
				name: 'payment_term',
				type: 'string',
				default: '',
				description:
					'The timeframe in which the invoice should be paid. Defaults to custom. Options: upon receipt, net 15, net 30, net 45, or net 60.',
			},
			{
				displayName: 'Purchase Order',
				name: 'purchase_order',
				type: 'string',
				default: '',
				description: 'The purchase order number',
			},
			{
				displayName: 'Retainer ID',
				name: 'retainer_id',
				type: 'boolean',
				default: true,
				// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
				description: 'The ID of the retainer associated with this invoice',
			},
			{
				displayName: 'Subject',
				name: 'subject',
				type: 'string',
				default: '',
				description: 'The invoice subject',
			},
			{
				displayName: 'Tax',
				name: 'tax',
				type: 'string',
				default: '',
				description:
					'This percentage is applied to the subtotal, including line items and discounts. Example: use 10.0 for 10.0%.',
			},
			{
				displayName: 'Tax2',
				name: 'tax2',
				type: 'string',
				default: '',
				description:
					'This percentage is applied to the subtotal, including line items and discounts. Example: use 10.0 for 10.0%.',
			},
		],
	},

	/* -------------------------------------------------------------------------- */
	/*                                invoice:update                              */
	/* -------------------------------------------------------------------------- */
	{
		displayName: 'Invoice ID',
		name: 'id',
		type: 'string',
		default: '',
		required: true,
		displayOptions: {
			show: {
				operation: ['update'],
				resource,
			},
		},
		description: 'The ID of the invoice want to update',
	},
	{
		displayName: 'Update Fields',
		name: 'updateFields',
		type: 'collection',
		placeholder: 'Add Field',
		displayOptions: {
			show: {
				operation: ['update'],
				resource,
			},
		},
		default: {},
		options: [
			{
				displayName: 'Client ID',
				name: 'client_id',
				type: 'string',
				default: '',
				description: 'The ID of the retainer associated with this invoice',
			},
			{
				displayName: 'Currency',
				name: 'currency',
				type: 'string',
				default: '',
				description:
					'The currency used by the invoice. If not provided, the client’s currency will be used. See a list of supported currencies',
			},
			{
				displayName: 'Discount',
				name: 'over_budget_notification_percentage',
				type: 'string',
				default: '',
				description:
					'This percentage is subtracted from the subtotal. Example: use 10.0 for 10.0%.',
			},
			{
				displayName: 'Due Date',
				name: 'ends_on',
				type: 'dateTime',
				default: '',
				description:
					'Date the invoice is due. Defaults to the issue_date if no payment_term is specified.',
			},
			{
				displayName: 'Estimate ID',
				name: 'estimate_id',
				type: 'string',
				default: '',
				description: 'The ID of the estimate associated with this invoice',
			},
			{
				displayName: 'Issue Date',
				name: 'issue_date',
				type: 'dateTime',
				default: '',
				description: 'Date the invoice was issued. Defaults to today’s date.',
			},
			{
				displayName: 'Notes',
				name: 'notes',
				type: 'string',
				default: '',
				description: 'Notes about the project',
			},
			{
				displayName: 'Number',
				name: 'number',
				type: 'string',
				default: '',
				description: 'If no value is set, the number will be automatically generated',
			},
			{
				displayName: 'Payment Term',
				name: 'payment_term',
				type: 'string',
				default: '',
				description:
					'The timeframe in which the invoice should be paid. Defaults to custom. Options: upon receipt, net 15, net 30, net 45, or net 60.',
			},
			{
				displayName: 'Purchase Order',
				name: 'purchase_order',
				type: 'string',
				default: '',
				description: 'The purchase order number',
			},
			{
				displayName: 'Retainer ID',
				name: 'retainer_id',
				type: 'boolean',
				default: true,
				// eslint-disable-next-line n8n-nodes-base/node-param-description-boolean-without-whether
				description: 'The ID of the retainer associated with this invoice',
			},
			{
				displayName: 'Subject',
				name: 'subject',
				type: 'string',
				default: '',
				description: 'The invoice subject',
			},
			{
				displayName: 'Tax',
				name: 'tax',
				type: 'string',
				default: '',
				description:
					'This percentage is applied to the subtotal, including line items and discounts. Example: use 10.0 for 10.0%.',
			},
			{
				displayName: 'Tax2',
				name: 'tax2',
				type: 'string',
				default: '',
				description:
					'This percentage is applied to the subtotal, including line items and discounts. Example: use 10.0 for 10.0%.',
			},
		],
	},
];


import { INodeProperties } from 'n8n-workflow';

export const campaignOperations: INodeProperties[] = [
	{
		displayName: 'Operation',
		name: 'operation',
		type: 'options',
		default: 'get',
		noDataExpression: true,
		options: [
			{
				name: 'Add Contact',
				value: 'addContact',
				action: 'Add a contact to a campaign',
			},
			{
				name: 'Create',
				value: 'create',
				action: 'Create a campaign',
			},
			{
				name: 'Duplicate',
				value: 'duplicate',
				action: 'Duplicate a campaign',
			},
			{
				name: 'Get',
				value: 'get',
				action: 'Get a campaign',
			},
			{
				name: 'Get Many',
				value: 'getAll',
				action: 'Get many campaigns',
			},
			{
				name: 'Pause',
				value: 'pause',
				action: 'Pause a campaign',
			},
			{
				name: 'Start',
				value: 'start',
				action: 'Start a campaign',
			},
		],
		displayOptions: {
			show: {
				resource: ['campaign'],
			},
		},
	},
];

export const campaignFields: INodeProperties[] = [
	// ----------------------------------
	//       campaign: addContact
	// ----------------------------------
	{
		displayName: 'Campaign Name or ID',
		name: 'campaignId',
		type: 'options',
		typeOptions: {
			loadOptionsMethod: 'getCampaigns',
		},
		default: [],
		required: true,
		description:
			'The ID of the campaign to add the contact to. Choose from the list, or specify an ID using an expression.',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['addContact'],
			},
		},
	},
	{
		displayName: 'Contact Email',
		name: 'contactEmail',
		type: 'string',
		required: true,
		default: '',
		description: 'The email of the contact to add to the campaign',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['addContact'],
			},
		},
	},
	{
		displayName: 'Additional Fields',
		name: 'additionalFields',
		type: 'collection',
		placeholder: 'Add Field',
		default: {},
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['addContact'],
			},
		},
		options: [
			{
				displayName: 'Custom Fields',
				name: 'customFieldsUi',
				placeholder: 'Add Custom Field',
				type: 'fixedCollection',
				typeOptions: {
					multipleValues: true,
				},
				description: 'Filter by custom fields',
				default: {},
				options: [
					{
						name: 'customFieldsValues',
						displayName: 'Custom Field',
						values: [
							{
								displayName: 'Field Name',
								name: 'fieldName',
								type: 'string',
								default: '',
								description: 'The name of the field to add custom field to',
							},
							{
								displayName: 'Value',
								name: 'value',
								type: 'string',
								default: '',
								description: 'The value to set on custom field',
							},
						],
					},
				],
			},
			{
				displayName: 'First Name',
				name: 'firstName',
				type: 'string',
				default: '',
				description: 'First name of the contact to add',
			},
			{
				displayName: 'Last Contacted',
				name: 'lastContacted',
				type: 'dateTime',
				default: '',
				description: 'Last contacted date of the contact to add',
			},
			{
				displayName: 'Last Name',
				name: 'lastName',
				type: 'string',
				default: '',
				description: 'Last name of the contact to add',
			},
			{
				displayName: 'Last Open',
				name: 'lastOpen',
				type: 'dateTime',
				default: '',
				description: 'Last opened date of the contact to add',
			},
			{
				displayName: 'Last Replied',
				name: 'lastReplied',
				type: 'dateTime',
				default: '',
				description: 'Last replied date of the contact to add',
			},
			{
				displayName: 'Mails Sent',
				name: 'mailsSent',
				type: 'number',
				default: 0,
				description: 'Number of emails sent to the contact to add',
			},
			{
				displayName: 'Phone Number',
				name: 'phoneNumber',
				type: 'string',
				default: '',
				description: 'Phone number of the contact to add',
			},
		],
	},

	// ----------------------------------
	//         campaign: create
	// ----------------------------------
	{
		displayName: 'Campaign Name',
		name: 'campaignName',
		type: 'string',
		required: true,
		default: '',
		description: 'The name of the campaign to create',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['create'],
			},
		},
	},

	// ----------------------------------
	//       campaign: get
	// ----------------------------------
	{
		displayName: 'Campaign ID',
		name: 'campaignId',
		type: 'string',
		default: '',
		required: true,
		description: 'The ID of the campaign to retrieve',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['get'],
			},
		},
	},

	// ----------------------------------
	//       campaign: getAll
	// ----------------------------------
	{
		displayName: 'Return All',
		name: 'returnAll',
		type: 'boolean',
		default: false,
		description: 'Whether to return all results or only up to a given limit',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['getAll'],
			},
		},
	},
	{
		displayName: 'Limit',
		name: 'limit',
		type: 'number',
		default: 100,
		description: 'Max number of results to return',
		typeOptions: {
			minValue: 1,
			maxValue: 100,
		},
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['getAll'],
				returnAll: [false],
			},
		},
	},

	// ----------------------------------
	//       campaign: pause
	// ----------------------------------
	{
		displayName: 'Campaign ID',
		name: 'campaignId',
		type: 'string',
		default: '',
		required: true,
		description: 'The ID of the campaign to pause. The campaign must be in RUNNING mode.',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['pause'],
			},
		},
	},

	// ----------------------------------
	//       campaign: start
	// ----------------------------------
	{
		displayName: 'Campaign ID',
		name: 'campaignId',
		type: 'string',
		default: '',
		required: true,
		description: 'The ID of the campaign to start. Email provider and contacts must be set.',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['start'],
			},
		},
	},

	// ----------------------------------
	//       campaign: duplicate
	// ----------------------------------
	{
		displayName: 'Campaign Name or ID',
		name: 'campaignId',
		type: 'options',
		default: '',
		required: true,
		description:
			'The ID of the campaign to duplicate. Choose from the list, or specify an ID using an expression.',
		typeOptions: {
			loadOptionsMethod: 'getCampaigns',
		},
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['duplicate'],
			},
		},
	},
	{
		displayName: 'New Campaign Name',
		name: 'campaignName',
		type: 'string',
		required: true,
		default: '',
		description: 'The name of the new campaign to create',
		displayOptions: {
			show: {
				resource: ['campaign'],
				operation: ['duplicate'],
			},
		},
	},
	{
		displayName: 'Options',
		name: 'options',
		type: 'collection',
		default: {},
		placeholder: 'Add Field',
		displayOptions: {
			show: {
				operation: ['duplicate'],
				resource: ['campaign'],
			},
		},
		options: [
			{
				displayName: 'Copy Contacts',
				name: 'copyContacts',
				type: 'boolean',
				default: false,
				description: 'Whether to copy all the contacts from the original campaign',
			},
			{
				displayName: 'Copy Email Provider',
				name: 'copyProvider',
				type: 'boolean',
				default: true,
				description: 'Whether to set the same email provider than the original campaign',
			},
			{
				displayName: 'Copy Email Sequence',
				name: 'copyMails',
				type: 'boolean',
				default: true,
				description:
					'Whether to copy all the steps of the email sequence from the original campaign',
			},
			{
				displayName: 'Copy Global Settings',
				name: 'copySettings',
				type: 'boolean',
				default: true,
				description: 'Whether to copy all the general settings from the original campaign',
			},
		],
	},
];


return option + this.$locale.baseText('ndv.output.of') + (this.maxRunIndex+1) + itemsLabel;

getDataCount(runIndex: number, outputIndex: number) {

const runData: IRunData | null = this.workflowRunData;

if (this.pinData) {
return this.pinData.length;
}