Перейти к содержимому
GitHubXDiscord

createRuntime

Стабильный · с 0.1.0

createRuntime возвращает изолированный Runtime — контейнер, в котором живут триггеры, условия и действия для дерева компонентов. Большинство приложений создают один рантайм в main.tsx и пробрасывают его через <TriggerRuntimeProvider>. Если пропустить вызов полностью, Triggery использует лениво создаваемый рантайм по умолчанию через getDefaultRuntime.

import { createRuntime } from '@triggery/core';
function createRuntime(options?: RuntimeOptions): Runtime;
ПараметрТипПо умолчаниюОписание
inspectorboolean | { dev?: boolean; prod?: boolean }DEV true, PROD falseВключить / выключить per-run инспектор.
inspectorBufferSizenumber50Размер кольцевого буфера инспектора. Игнорируется, если инспектор отключён.
middlewarereadonly Middleware[][]Цепочка миддлвэров.
maxCascadeDepthnumber3Максимальная глубина каскада — action → fireEvent → …. Запуски глубже пропускаются со статусом 'overflow'.

Полную форму смотри в RuntimeOptions.

Объект Runtime. Методы, которыми пользуется большинство приложений:

МетодОписание
runtime.fire(event, payload)Диспатчит событие через планировщик. Возвращает void.
runtime.fireSync(event, payload)Диспатчит синхронно (минуя планировщик). Для тестов и бенчмарков.
runtime.subscribe(listener)Слушать каждый записанный запуск. Возвращает RegistrationToken.
runtime.getInspectorBuffer()Последние N снепшотов инспектора.
runtime.getTrigger(id)Найти зарегистрированный триггер.
runtime.graph()JSON-friendly снепшот реестра — используется CLI triggery graph.
runtime.dispose()Прервать все запуски в полёте и сбросить все регистрации.

Методы register* (registerTrigger, registerCondition, registerAction) тоже часть поверхности, но их за тебя вызывают биндинги.

import { createRuntime } from '@triggery/core';
import { TriggerRuntimeProvider } from '@triggery/react';
import type { ComponentType } from 'react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

const runtime = createRuntime();

declare const App: ComponentType;
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <TriggerRuntimeProvider runtime={runtime}>
      <App />
    </TriggerRuntimeProvider>
  </StrictMode>,
);
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';
import { afterEachfunction afterEach<ExtraContext = object>(fn: AfterEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
, beforeEachfunction beforeEach<ExtraContext = object>(fn: BeforeEachListener<ExtraContext>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
} from 'vitest';
let runtimelet runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime(); beforeEachbeforeEach<object>(fn: BeforeEachListener<object>, timeout?: number): void
Registers a callback function to be executed before each test within the current suite. This hook is useful for scenarios where you need to reset or reinitialize the test environment before each test runs, such as resetting database states, clearing caches, or reinitializing variables. **Note:** The `beforeEach` hooks are executed in the order they are defined one after another. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed before each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using beforeEach to reset a database state beforeEach(async () => { await database.reset(); }); ```
(() => {
runtimelet runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ inspectorBufferSizeinspectorBufferSize?: number | undefined
Inspector ring buffer size (default: 50). Ignored when the inspector is disabled.
: 100 });
}); afterEachafterEach<object>(fn: AfterEachListener<object>, timeout?: number): void
Registers a callback function to be executed after each test within the current suite has completed. This hook is useful for scenarios where you need to clean up or reset the test environment after each test runs, such as deleting temporary files, clearing test-specific database entries, or resetting mocked functions. **Note:** The `afterEach` hooks are running in reverse order of their registration. You can configure this by changing the `sequence.hooks` option in the config file.
@paramfn - The callback function to be executed after each test. This function receives an `TestContext` parameter if additional test context is needed.@paramtimeout - Optional timeout in milliseconds for the hook. If not provided, the default hook timeout from the runner's configuration is used.@returns@example```ts // Example of using afterEach to delete temporary files created during a test afterEach(async () => { await fileSystem.deleteTempFiles(); }); ```
(() => {
runtimelet runtime: Runtime.disposefunction dispose(): void
Tear down the runtime completely.
();
});
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({
  maxCascadeDepthmaxCascadeDepth?: number | undefined
Maximum cascade depth (action → fireEvent → ...). Default: 3.
: 1, // refuse any indirect chain — action→event→trigger is enough
});
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime, type Middleware
type Middleware = {
    readonly name: string;
    onFire?(ctx: FireContext): void | {
        cancel: true;
        reason: string;
    };
    onBeforeMatch?(ctx: MatchContext): void;
    onSkip?(ctx: SkipContext): void;
    onActionStart?(ctx: ActionContext): void;
    onActionEnd?(ctx: ActionContext & {
        durationMs: number;
        result?: unknown;
    }): void;
    onError?(ctx: ActionContext & {
        error: unknown;
    }): void;
    onCascade?(ctx: CascadeContext): void;
}
} from '@triggery/core';
const loggerconst logger: Middleware: Middleware
type Middleware = {
    readonly name: string;
    onFire?(ctx: FireContext): void | {
        cancel: true;
        reason: string;
    };
    onBeforeMatch?(ctx: MatchContext): void;
    onSkip?(ctx: SkipContext): void;
    onActionStart?(ctx: ActionContext): void;
    onActionEnd?(ctx: ActionContext & {
        durationMs: number;
        result?: unknown;
    }): void;
    onError?(ctx: ActionContext & {
        error: unknown;
    }): void;
    onCascade?(ctx: CascadeContext): void;
}
= {
namename: string: 'logger', onActionEnd
onActionEnd?(ctx: ActionContext & {
    durationMs: number;
    result?: unknown;
}): void
({ triggerIdtriggerId: string, actionNameactionName: string, durationMsdurationMs: number }) {
consolevar console: Console.logConsole.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
(`[${triggerIdtriggerId: string}] ${actionNameactionName: string} ${durationMsdurationMs: number.toFixedNumber.toFixed(fractionDigits?: number): string
Returns a string representing a number in fixed-point notation.
@paramfractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
(2)}ms`);
}, }; const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ middlewaremiddleware?: readonly Middleware[] | undefined
Global middleware applied to every trigger in this runtime.
: [loggerconst logger: Middleware] });
import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({ inspectorinspector?: InspectorOption | undefined
Enable / disable the per-run inspector. See {@link InspectorOption } .
: false });

Или по окружениям:

import { createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime } from '@triggery/core';

const runtimeconst runtime: Runtime = createRuntimefunction createRuntime(options?: RuntimeOptions): Runtime({
  inspectorinspector?: InspectorOption | undefined
Enable / disable the per-run inspector. See {@link InspectorOption } .
: { devdev?: boolean | undefined: true, prodprod?: boolean | undefined: false },
});