@hugex/ai 2.8.15 → 2.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/chunk-3TXHFKDN.js +1 -0
  2. package/dist/{chunk-TUI5H3ZB.js → chunk-G3SGJ7XJ.js} +1 -1
  3. package/dist/chunk-R6EKV3WR.js +1 -0
  4. package/dist/{chunk-43NDF544.js → chunk-RYHQGPX5.js} +1 -1
  5. package/dist/client/hooks/useAgent.d.ts +31 -0
  6. package/dist/client/states/agent-store.d.ts +95 -0
  7. package/dist/client.d.ts +4 -129
  8. package/dist/client.js +1 -1
  9. package/dist/common/constants/ai-models.d.ts +10 -0
  10. package/dist/common/constants/tools-registry.d.ts +8 -0
  11. package/dist/common/types/agent-types.d.ts +61 -0
  12. package/dist/common/types/ai-models-types.d.ts +94 -0
  13. package/dist/common/types/memory-types.d.ts +28 -0
  14. package/dist/common/types/node-types.d.ts +9 -0
  15. package/dist/common/types/user-types.d.ts +11 -0
  16. package/dist/common/types/var-mapping.d.ts +29 -0
  17. package/dist/common/types/ws-message.d.ts +58 -0
  18. package/dist/common/utils/agent-utils.d.ts +0 -0
  19. package/dist/common/utils/generationParams.d.ts +19 -0
  20. package/dist/common/utils/logc.d.ts +17 -0
  21. package/dist/common/utils/reasoning.d.ts +32 -0
  22. package/dist/common/utils/templateUtils.d.ts +7 -0
  23. package/dist/common.d.ts +12 -362
  24. package/dist/common.js +1 -1
  25. package/dist/{composioTool-EXCSM6F4.js → composioTool-TVURCFXP.js} +1 -1
  26. package/dist/convertTempMessure-5CAGRLBY.js +1 -0
  27. package/dist/{httpTool-EU63HPF5.js → httpTool-NTDDXZZE.js} +1 -1
  28. package/dist/index.d.ts +27 -431
  29. package/dist/index.js +13 -13
  30. package/dist/{oraApi-3JWDQQUE.js → oraApi-YIJGMXX7.js} +1 -1
  31. package/dist/{recall-SD6FENAS.js → recall-IABRCSHY.js} +1 -1
  32. package/dist/server/api/agents.d.ts +1 -0
  33. package/dist/server/api/auth.d.ts +1 -0
  34. package/dist/server/api/commons.d.ts +1 -0
  35. package/dist/server/api/composio.d.ts +1 -0
  36. package/dist/server/api/instances.d.ts +1 -0
  37. package/dist/server/core/AgentDO.d.ts +80 -0
  38. package/dist/server/core/AgentHTTP.d.ts +2 -0
  39. package/dist/server/logic/FlowEngine.d.ts +38 -0
  40. package/dist/server/logic/llm/files.d.ts +2 -0
  41. package/dist/server/logic/llm/images.d.ts +5 -0
  42. package/dist/server/logic/serverMessages.d.ts +13 -0
  43. package/dist/server/runners/answerNodeRunner.d.ts +4 -0
  44. package/dist/server/runners/apiNodeRunner.d.ts +4 -0
  45. package/dist/server/runners/classifierNodeRunner.d.ts +6 -0
  46. package/dist/server/runners/llmNodeRunner.d.ts +6 -0
  47. package/dist/server/runners/memoNodeRunner.d.ts +4 -0
  48. package/dist/server/runners/startNodeRunner.d.ts +4 -0
  49. package/dist/server/sql/agentSQL.d.ts +24 -0
  50. package/dist/server/tools/composioTool.d.ts +4 -0
  51. package/dist/server/tools/convertTempMessure.d.ts +15 -0
  52. package/dist/server/tools/httpTool.d.ts +18 -0
  53. package/dist/server/tools/recall.d.ts +7 -0
  54. package/dist/server/tools/skillTool.d.ts +6 -0
  55. package/dist/server/tools/tempTool.d.ts +4 -0
  56. package/dist/server/tools/twitter.d.ts +5 -0
  57. package/dist/server/tools/vectorize.d.ts +6 -0
  58. package/dist/server/types/node.d.ts +25 -0
  59. package/dist/server/utils/apiUtils.d.ts +14 -0
  60. package/dist/server/utils/auth.d.ts +3 -0
  61. package/dist/server/utils/composio.d.ts +114 -0
  62. package/dist/server/utils/contextMemory.d.ts +25 -0
  63. package/dist/server/utils/cookies.d.ts +1 -0
  64. package/dist/server/utils/coreApi.d.ts +7 -0
  65. package/dist/server/utils/embeddings.d.ts +3 -0
  66. package/dist/server/utils/flowRefresh.d.ts +22 -0
  67. package/dist/server/utils/flowValidation.d.ts +2 -0
  68. package/dist/server/utils/jsonSchemaToZod.d.ts +12 -0
  69. package/dist/server/utils/modelProvider.d.ts +20 -0
  70. package/dist/server/utils/oraApi.d.ts +6 -0
  71. package/dist/server/utils/oraExtract.d.ts +11 -0
  72. package/dist/server/utils/secrets.d.ts +2 -0
  73. package/dist/server/utils/secretsRefs.d.ts +6 -0
  74. package/dist/server/utils/sessionEnvMemory.d.ts +12 -0
  75. package/dist/server/utils/sessionIndex.d.ts +16 -0
  76. package/dist/server/utils/telemetry.d.ts +10 -0
  77. package/dist/server/utils/templateUtils.d.ts +7 -0
  78. package/dist/{skillTool-Y5GZ4ZAR.js → skillTool-BSQFKZGK.js} +1 -1
  79. package/dist/tempTool-2RXAF56M.js +1 -0
  80. package/dist/{twitter-QNCTAE4E.js → twitter-OMDEG7T2.js} +1 -1
  81. package/dist/vectorize-UJXIDL2E.js +1 -0
  82. package/package.json +19 -19
  83. package/dist/chunk-2JN3IX2Y.js +0 -1
  84. package/dist/chunk-6BYZCJPP.js +0 -1
  85. package/dist/convertTempMessure-TT7DIP6C.js +0 -1
  86. package/dist/magic-string.es-S3C7UPCH.js +0 -13
  87. package/dist/skillTool.test-6UDHQARG.js +0 -190
  88. package/dist/tempTool-6Q6C4HEJ.js +0 -1
  89. package/dist/vectorize-SQROWLSU.js +0 -1
@@ -0,0 +1,24 @@
1
+ import type { Message } from '../../common/types/agent-types';
2
+ import type { ContextIndexEntry, ContextRow, ContextUpsertInput } from '../../common/types/memory-types';
3
+ export type SqlContext = {
4
+ sql: any;
5
+ };
6
+ export declare function ensureMessagesTable(ctx: SqlContext): Promise<void>;
7
+ export declare function setMessage(ctx: SqlContext, msg: Message): Promise<void>;
8
+ export declare function getAllMessages(ctx: SqlContext): Promise<Message[]>;
9
+ export declare function clearAllMessages(ctx: SqlContext): Promise<void>;
10
+ export declare function ensureContextTable(ctx: SqlContext): Promise<void>;
11
+ export declare function setContext(ctx: SqlContext, row: ContextUpsertInput): Promise<void>;
12
+ export declare function getContextIndex(ctx: SqlContext): Promise<ContextIndexEntry[]>;
13
+ export declare function getContext(ctx: SqlContext, ref: string): Promise<ContextRow | null>;
14
+ export declare function getContextData(ctx: SqlContext, ref: string): Promise<string | null>;
15
+ /**
16
+ * Resolve a context ref the model echoed back: exact match first, else a unique prefix match
17
+ * (the working-memory block exposes shortened hash tails). Ambiguous prefixes resolve to null.
18
+ */
19
+ export declare function resolveContextRef(ctx: SqlContext, ref: string): Promise<ContextRow | null>;
20
+ /** Evict tool-domain rows up to and including a cycle (used after a summary folds them in). */
21
+ export declare function deleteContextToolsUpToCycle(ctx: SqlContext, cycle: number): Promise<void>;
22
+ export declare function getMaxContextCycle(ctx: SqlContext): Promise<number>;
23
+ export declare function clearAllContext(ctx: SqlContext): Promise<void>;
24
+ export declare function ensureAgentTables(ctx: SqlContext): Promise<void>;
@@ -0,0 +1,4 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
3
+ import type { ToolRow } from './httpTool';
4
+ export declare function loadComposioTools(row: ToolRow, sessionEnv: SessionEnv, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void): Promise<Record<string, any>>;
@@ -0,0 +1,15 @@
1
+ import { type Tool } from 'ai';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ import type { FlowEngineState } from '../logic/FlowEngine';
4
+ /**
5
+ * Temperature conversion tool with static parameter support
6
+ *
7
+ * Usage examples:
8
+ * - Static params (node.tools): { id: 'convertTempMessure', params: { source: 'C', target: 'F' } }
9
+ * - Runtime override: convertTempMessure.execute({ temperature: 25, source: 'C', target: 'K' })
10
+ * - Mixed: Static params set defaults, runtime args can override
11
+ */
12
+ export declare function convertTempMessure(sessionEnv: SessionEnv, engineState: FlowEngineState, opts?: {
13
+ source?: string;
14
+ target?: string;
15
+ }, onServerEvent?: (event: any) => void): Tool;
@@ -0,0 +1,18 @@
1
+ import { type Tool } from 'ai';
2
+ import type { FlowEngineState } from '../logic/FlowEngine';
3
+ import type { SessionEnv } from '../core/AgentDO';
4
+ export interface ToolRow {
5
+ id: string;
6
+ tenant: string;
7
+ name: string;
8
+ label?: string;
9
+ description?: string;
10
+ status?: string;
11
+ kind: string;
12
+ inputSchema?: any;
13
+ execution?: any;
14
+ output?: any;
15
+ secretsRefs?: any;
16
+ }
17
+ export declare function customHttpTool(row: ToolRow, sessionEnv: SessionEnv, engineState: FlowEngineState, onServerEvent?: (event: any) => void): Tool;
18
+ export default customHttpTool;
@@ -0,0 +1,7 @@
1
+ import { type Tool } from 'ai';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ import type { FlowEngineState } from '../logic/FlowEngine';
4
+ export declare function recall(sessionEnv: SessionEnv, _engineState: FlowEngineState, _opts?: unknown, onServerEvent?: (event: {
5
+ type: string;
6
+ content: unknown;
7
+ }) => void): Tool;
@@ -0,0 +1,6 @@
1
+ import { type Tool } from 'ai';
2
+ import type { ToolRow } from './httpTool';
3
+ import type { SessionEnv } from '../core/AgentDO';
4
+ import type { FlowEngineState } from '../logic/FlowEngine';
5
+ export declare function skillTool(row: ToolRow, _sessionEnv: SessionEnv, _engineState: FlowEngineState, onServerEvent?: (event: any) => void): Tool;
6
+ export declare function readSkillRef(sessionEnv: SessionEnv, skillRows: ToolRow[], _engineState: FlowEngineState, onServerEvent?: (event: any) => void): Tool;
@@ -0,0 +1,4 @@
1
+ import { type Tool } from 'ai';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ import type { FlowEngineState } from '../logic/FlowEngine';
4
+ export declare const tempTool: (sessionEnv: SessionEnv, engineState: FlowEngineState, opts?: any, onServerEvent?: (event: any) => void) => Tool;
@@ -0,0 +1,5 @@
1
+ import { type Tool } from 'ai';
2
+ import type { FlowEngineState } from '../logic/FlowEngine';
3
+ import type { SessionEnv } from '../core/AgentDO';
4
+ export declare function twitter(sessionEnv: SessionEnv, engineState: FlowEngineState, opts?: any, onServerEvent?: (event: any) => void): Tool;
5
+ export default twitter;
@@ -0,0 +1,6 @@
1
+ import { type Tool } from 'ai';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ import type { FlowEngineState } from '../logic/FlowEngine';
4
+ export declare function vectorize(sessionEnv: SessionEnv, engineState: FlowEngineState, opts?: {
5
+ namespace?: string;
6
+ }): Tool;
@@ -0,0 +1,25 @@
1
+ export interface FlowNode {
2
+ id: string;
3
+ type: string;
4
+ data: any;
5
+ }
6
+ export interface FlowEdge {
7
+ id: string;
8
+ source: string;
9
+ target: string;
10
+ sourceHandle?: string;
11
+ }
12
+ export interface FlowState {
13
+ nodes: FlowNode[];
14
+ edges: FlowEdge[];
15
+ }
16
+ export interface FlowData {
17
+ tenant: string;
18
+ flowId: string;
19
+ chatId: string;
20
+ state?: FlowState;
21
+ /** Monotonic version from FlowDO, bumped on every state save. Undefined for flows
22
+ * never re-saved since versioning shipped — treated as "unknown", never stale. */
23
+ stateVersion?: number;
24
+ detail?: Record<string, any>;
25
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Safely parse JSON string, with fallback to extract JSON-like objects
3
+ * @param s - The string to parse
4
+ * @returns Parsed JSON object or null if parsing fails
5
+ */
6
+ export declare const safeParseJSON: (s: string) => any;
7
+ /**
8
+ * Build a URL with query parameters
9
+ * @param base - Base URL
10
+ * @param path - Path to append
11
+ * @param params - Query parameters object
12
+ * @returns Full URL string
13
+ */
14
+ export declare const buildUrl: (base: string, path: string, params?: Record<string, any>) => string;
@@ -0,0 +1,3 @@
1
+ import type { UserInterface } from 'lib/common/types/user-types';
2
+ export declare function verifyUser(request: Request, env: Env, ctx: ExecutionContext): Promise<boolean | UserInterface | null>;
3
+ export declare function verifyToken(env: Env, token?: string | null): Promise<any>;
@@ -0,0 +1,114 @@
1
+ import type { FlowEngineState } from '../logic/FlowEngine';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ export type ComposioAuthMode = 'in_app' | 'manual';
4
+ export type ComposioToolkitToolsConfig = {
5
+ enable?: string[];
6
+ disable?: string[];
7
+ };
8
+ /** Composio session API expects `{ enable: string[] }` or `{ disable: string[] }`, not both optional. */
9
+ export type ComposioSessionToolsConfig = Record<string, {
10
+ enable: string[];
11
+ } | {
12
+ disable: string[];
13
+ }>;
14
+ export type ComposioExecution = {
15
+ toolkits: string[];
16
+ authMode?: ComposioAuthMode;
17
+ authConfigs?: Record<string, string>;
18
+ /** Stable scope for manual connections before tool row id exists (new-tool draft). */
19
+ connectionScope?: string;
20
+ /** @deprecated Legacy preload list; migrated to tools.enable on read. Use sessionPreload for Composio SDK preload. */
21
+ preload?: {
22
+ tools?: string[];
23
+ };
24
+ tools?: Record<string, ComposioToolkitToolsConfig>;
25
+ manageConnections?: {
26
+ callbackUrl?: string;
27
+ };
28
+ workbench?: {
29
+ enable?: boolean;
30
+ };
31
+ /** Expose allowed tools directly in session.tools() (Composio direct_tools preset). */
32
+ sessionPreset?: 'direct_tools';
33
+ /** Preload selected tools into session.tools() while keeping meta tools (ignored when sessionPreset is direct_tools). */
34
+ sessionPreload?: {
35
+ enabled?: boolean;
36
+ };
37
+ };
38
+ export declare function resolveComposioConnectionScope(execution: {
39
+ connectionScope?: string;
40
+ }, toolRowId?: string): string | undefined;
41
+ /** Composio entity id for manual (shared) tool credentials. */
42
+ export declare function scopeComposioUserId(scope: string): string;
43
+ export type ComposioCtx = {
44
+ flowId: string;
45
+ sessionId: string;
46
+ toolRowId?: string;
47
+ toolkit?: string;
48
+ };
49
+ export declare function resolvePublicOrigin(sessionEnv: SessionEnv): string;
50
+ export declare function resolveComposioApiKey(sessionEnv: SessionEnv): string;
51
+ export type ComposioSessionMeta = {
52
+ sessionId: string;
53
+ userId: string;
54
+ /** Fingerprint of execution config; mismatch forces a new Composio session. */
55
+ configKey?: string;
56
+ };
57
+ export type ComposioSessionCreateOverrides = {
58
+ manageConnections: false | {
59
+ callbackUrl: string;
60
+ };
61
+ workbench: {
62
+ enable: boolean;
63
+ };
64
+ };
65
+ /** Flatten all tools.enable slugs from the per-toolkit allowlist. */
66
+ export declare function flattenEnabledToolSlugs(tools: Record<string, ComposioToolkitToolsConfig> | undefined): string[];
67
+ /** Stable key for Composio session reuse when execution config is unchanged. */
68
+ export declare function composioSessionConfigKey(execution: ComposioExecution): string;
69
+ export declare function buildComposioSessionCreateOptions(execution: ComposioExecution, overrides: ComposioSessionCreateOverrides): {
70
+ toolkits: string[];
71
+ authConfigs?: Record<string, string> | undefined;
72
+ tools?: ComposioSessionToolsConfig | undefined;
73
+ manageConnections: false | {
74
+ callbackUrl: string;
75
+ };
76
+ workbench: {
77
+ enable: boolean;
78
+ };
79
+ sessionPreset?: "direct_tools" | undefined;
80
+ preload: {
81
+ tools: string[];
82
+ };
83
+ } | {
84
+ toolkits: string[];
85
+ authConfigs?: Record<string, string> | undefined;
86
+ tools?: ComposioSessionToolsConfig | undefined;
87
+ manageConnections: false | {
88
+ callbackUrl: string;
89
+ };
90
+ workbench: {
91
+ enable: boolean;
92
+ };
93
+ sessionPreset?: "direct_tools" | undefined;
94
+ preload?: undefined;
95
+ };
96
+ export declare function composioUserId(sessionEnv: SessionEnv, engineState: FlowEngineState, options?: {
97
+ allowChatIdFallback?: boolean;
98
+ }): string;
99
+ export declare function encodeCtx(ctx: ComposioCtx): string;
100
+ export declare function decodeCtx(encoded: string): ComposioCtx | null;
101
+ export declare function publicOrigin(env?: Env): string;
102
+ export declare function buildCallbackUrl(sessionEnv: SessionEnv, flowId?: string, chatSessionId?: string, toolRowId?: string): string;
103
+ export declare function toComposioSessionToolsConfig(tools: Record<string, ComposioToolkitToolsConfig> | undefined): ComposioSessionToolsConfig | undefined;
104
+ export declare function parseComposioToolsConfig(raw: unknown, toolkits: string[], preload?: {
105
+ tools?: string[];
106
+ }): Record<string, ComposioToolkitToolsConfig> | undefined;
107
+ export declare function parseComposioExecution(raw: unknown): ComposioExecution;
108
+ /** In-app enables COMPOSIO_MANAGE_CONNECTIONS in chat; manual disables it and uses session.authorize(). */
109
+ export declare function resolveManageConnectionsConfig(execution: ComposioExecution, callbackUrl: string): false | {
110
+ callbackUrl: string;
111
+ };
112
+ export declare function looksLikeAuthError(err: unknown): boolean;
113
+ export declare function extractConnectLink(text: unknown): string | undefined;
114
+ export declare function extractToolkitHint(text: unknown, execution?: ComposioExecution): string | undefined;
@@ -0,0 +1,25 @@
1
+ import type { MemoryConfig, ContextIndexEntry } from '../../common/types/memory-types';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ /** Target cap for stored payloads (~256 KB). Hard ceiling stays under DO 2 MB row limit. */
4
+ export declare const DATA_CAP_BYTES: number;
5
+ export declare const DATA_HARD_CAP_BYTES: number;
6
+ export declare function buildMemoryConfig(startNodeData?: Record<string, unknown>): MemoryConfig;
7
+ /** Canonical JSON with sorted object keys for stable hashing. */
8
+ export declare function canonicalize(value: unknown): string;
9
+ export declare function hashParams(args: unknown): Promise<string>;
10
+ export declare function formatParams(args: unknown): string;
11
+ export declare function buildToolDescription(args: unknown, rawResult: unknown): string;
12
+ export declare function buildToolRef(toolName: string, args?: unknown): Promise<string>;
13
+ export declare function cheapSummary(result: unknown, maxLen?: number): string;
14
+ export declare function capData(raw: string): {
15
+ data: string;
16
+ truncated: boolean;
17
+ };
18
+ /** Shorten the hash tail of a tool/context ref so the model can echo it reliably in `recall`. */
19
+ export declare function shortRef(ref: string): string;
20
+ /** Max non-summary entries injected into the prompt; summaries are always kept. */
21
+ export declare const WORKING_MEMORY_MAX_ENTRIES = 40;
22
+ export declare function formatWorkingMemoryBlock(index: ContextIndexEntry[], maxEntries?: number): string;
23
+ export declare function summarizeCycle(agent: object, sessionEnv: SessionEnv, cycle: number): Promise<void>;
24
+ export declare function parseContextMeta(meta?: string): Record<string, unknown>;
25
+ export declare function mergeContextMeta(existing: string | undefined, patch: Record<string, unknown>): string;
@@ -0,0 +1 @@
1
+ export declare function parseCookies(cookieHeader: string | null | undefined): Record<string, string>;
@@ -0,0 +1,7 @@
1
+ export declare function fetchFlowKV(flowId: string, env: Env): Promise<unknown>;
2
+ export declare function fetchFlowState(flowId: string, env: Env): Promise<unknown>;
3
+ export declare function fetchEmbeddingsGet(hashes: string[], env: Env): Promise<unknown>;
4
+ export declare function fetchEmbeddingsPut(items: {
5
+ hash: string;
6
+ embedding: any;
7
+ }[], env: Env): Promise<unknown>;
@@ -0,0 +1,3 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ export declare const hashText: (text: string) => Promise<string>;
3
+ export declare const embedText: (sessionEnv: SessionEnv, text: string | string[], fallback?: boolean) => Promise<any>;
@@ -0,0 +1,22 @@
1
+ import type { FlowEngineState } from '../logic/FlowEngine';
2
+ export interface FlowRefreshResult {
3
+ engineState: FlowEngineState;
4
+ /** True when the flow's stateVersion actually changed — callers bust modelsCache + persist. */
5
+ refreshed: boolean;
6
+ }
7
+ /**
8
+ * Re-fetch the flow from hx-core each turn so a live session picks up designer edits (a node's
9
+ * model, prompt, etc.) instead of running a snapshot frozen at session start.
10
+ *
11
+ * ora holds NO direct FLOW_KV binding — all flow access goes through hx-core (API-key validated),
12
+ * which serves `GET /ora/flow/:id/state` from its own KV read/write-through cache. So this fetch is
13
+ * cheap on the backend even though it runs every turn.
14
+ *
15
+ * Only `flowData` is swapped; runtime state (`context`, `results`, `executedNodes`, `cycle`) is
16
+ * preserved. The `stateVersion` returned in the state payload tells us whether the flow actually
17
+ * changed — used to decide whether to bust the per-session `modelsCache`.
18
+ *
19
+ * Never throws: on any failure it returns the input unchanged so a turn is never blocked by the
20
+ * refresh (the session keeps its prior snapshot).
21
+ */
22
+ export declare function ensureFreshFlowData(env: Env | undefined, engineState: FlowEngineState): Promise<FlowRefreshResult>;
@@ -0,0 +1,2 @@
1
+ import type { FlowData } from '../types/node';
2
+ export declare function validateFlowStart(flow: FlowData): any;
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Converts a JSON Schema to a Zod schema.
4
+ * Supports object schemas with properties, arrays, and primitive types.
5
+ * Treats empty object ({}) as z.object({}).
6
+ * Supports nested object properties recursively; respects schema.required (makes properties optional unless required).
7
+ * A property `default` is an overridable fallback: it becomes z.default(...) so an
8
+ * omitted arg is filled (LLM-supplied value still wins). Precedence: default > required > optional.
9
+ * Supports arrays of primitives: { type: 'array', items: { type: 'string' } } -> z.array(z.string()).
10
+ * Returns z.any() for unsupported shapes as fallback.
11
+ */
12
+ export declare function jsonSchemaToZod(schema: any): z.ZodSchema;
@@ -0,0 +1,20 @@
1
+ import type { EffectiveParams, ModelEntry, ResolvedModel } from '../../common/types/ai-models-types';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ /** Normalize registry rows that may carry JSON columns as strings (D1 fallback). */
4
+ export declare function normalizeModelEntry(entry: ModelEntry): ModelEntry;
5
+ /**
6
+ * Resolves a model by its ID, returning a provider-agnostic handle suitable for `streamText`.
7
+ */
8
+ export declare function resolveModelById(modelId: string, sessionEnv?: SessionEnv, overrides?: EffectiveParams): Promise<ResolvedModel | undefined>;
9
+ /**
10
+ * Registers a custom provider resolver for runtime extension.
11
+ *
12
+ * @param name - The provider name to register.
13
+ * @param resolver - A function that takes a ModelEntry, optional SessionEnv, and optional overrides, returning the model handle.
14
+ *
15
+ * Example usage:
16
+ * ```typescript
17
+ * registerProvider('custom', (entry, sessionEnv, overrides) => customSDK(entry.providerModel, overrides));
18
+ * ```
19
+ */
20
+ export declare function registerProvider(name: string, resolver: (entry: ModelEntry, sessionEnv?: SessionEnv, overrides?: Record<string, any>) => Promise<any> | any): void;
@@ -0,0 +1,6 @@
1
+ export declare function fetchToolDefs(env: Env): Promise<any[]>;
2
+ export declare function fetchOraModel(modelId: string, env: Env): Promise<any>;
3
+ export declare function fetchSkillRef(env: Env, toolId: string, refName: string): Promise<{
4
+ name: string;
5
+ content: string;
6
+ }>;
@@ -0,0 +1,11 @@
1
+ type RawDocument = {
2
+ name: string;
3
+ mimeType: string;
4
+ data: string;
5
+ };
6
+ type ExtractedDocument = {
7
+ name: string;
8
+ text: string;
9
+ };
10
+ export declare function extractDocuments(documents: RawDocument[], env: Env | undefined): Promise<ExtractedDocument[]>;
11
+ export {};
@@ -0,0 +1,2 @@
1
+ export type SecretsMap = Readonly<Record<string, string>>;
2
+ export declare function loadTenantSecrets(env: Env, tenant: string | undefined | null): Promise<SecretsMap>;
@@ -0,0 +1,6 @@
1
+ export declare const SECRET_REF_RE: RegExp;
2
+ export declare const containsSecretRef: (template: string) => boolean;
3
+ export declare const AUTH_REF_RE: RegExp;
4
+ export declare const containsAuthRef: (template: string) => boolean;
5
+ export declare const containsCredRef: (template: string) => boolean;
6
+ export declare const scrubUrlForLog: (url: string) => string;
@@ -0,0 +1,12 @@
1
+ import type { SessionEnv } from '../core/AgentDO';
2
+ import type { FlowEngineState } from '../logic/FlowEngine';
3
+ import { type SqlContext } from '../sql/agentSQL';
4
+ export declare function findStartNodeData(engineState?: FlowEngineState): Record<string, unknown> | undefined;
5
+ export declare function resolveCycle(agent: SqlContext, engineState: FlowEngineState): Promise<number>;
6
+ export declare function buildMemorySessionEnv(agent: SqlContext, base: Omit<SessionEnv, 'memoryConfig' | 'cycle' | 'setContext' | 'getContextIndex' | 'getContextData' | 'getContext' | 'resolveContext' | 'pruneContext'>, engineState: FlowEngineState, cycle: number, onMemoryUpdated?: (ref: string) => void | Promise<void>): SessionEnv;
7
+ export declare function emitMemoryUpdated(onServerEvent: ((event: {
8
+ type: string;
9
+ content: unknown;
10
+ timestamp?: number;
11
+ }) => void | Promise<void>) | undefined, ref: string): Promise<void>;
12
+ export declare function newFlowEventId(): string;
@@ -0,0 +1,16 @@
1
+ import type { FlowEngineEvent } from '../logic/FlowEngine';
2
+ export interface SessionIndexInput {
3
+ id: string;
4
+ tenant: string;
5
+ flowId: string;
6
+ sessionId: string;
7
+ userId?: string | null;
8
+ title?: string | null;
9
+ turnTs: number;
10
+ events: FlowEngineEvent[];
11
+ }
12
+ /**
13
+ * Fire-and-forget index of a session turn to hx-ora: upserts the D1 sessions row
14
+ * and ships the turn's events to R2. Never throws into the turn — failures are logged.
15
+ */
16
+ export declare function indexSession(env: Env | undefined, input: SessionIndexInput): Promise<unknown>;
@@ -0,0 +1,10 @@
1
+ export interface TelemetryEvent {
2
+ userId?: string;
3
+ tenant?: string;
4
+ flowId?: string;
5
+ sessionId?: string;
6
+ type: string;
7
+ payload: any;
8
+ timestamp?: string;
9
+ }
10
+ export declare const sendEvent: (event: TelemetryEvent, env: Env) => Promise<void>;
@@ -0,0 +1,7 @@
1
+ import type { FlowEngineEvent, FlowEngineState } from '../logic/FlowEngine';
2
+ import type { SessionEnv } from '../core/AgentDO';
3
+ export declare function processTemplate(template: string, node: any, engineState: FlowEngineState, onServerEvent?: (event: FlowEngineEvent) => void, options?: {
4
+ callerTag?: string;
5
+ serializeNonStrings?: boolean;
6
+ sessionEnv?: SessionEnv;
7
+ }): string;
@@ -1 +1 @@
1
- import{a,b}from"./chunk-4FUIFBZO.js";import"./chunk-YHXUBVN2.js";import"./chunk-6BYZCJPP.js";export{b as readSkillRef,a as skillTool};
1
+ import{a,b}from"./chunk-4FUIFBZO.js";import"./chunk-YHXUBVN2.js";import"./chunk-3TXHFKDN.js";export{b as readSkillRef,a as skillTool};
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-R6EKV3WR.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as tempTool};
@@ -1 +1 @@
1
- import{a,b}from"./chunk-6HY7QUMP.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-6BYZCJPP.js";export{b as default,a as twitter};
1
+ import{a,b}from"./chunk-6HY7QUMP.js";import"./chunk-V6JSMX5A.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{b as default,a as twitter};
@@ -0,0 +1 @@
1
+ import{e as a}from"./chunk-G3SGJ7XJ.js";import"./chunk-U56YWPSI.js";import"./chunk-3TXHFKDN.js";export{a as vectorize};
package/package.json CHANGED
@@ -1,36 +1,36 @@
1
1
  {
2
2
  "name": "@hugex/ai",
3
- "version": "2.8.15",
3
+ "version": "2.9.4",
4
4
  "description": "Ora AI Agent Framework",
5
5
  "author": "a@hugex.co",
6
6
  "license": "SEE LICENSE IN LICENSE",
7
7
  "type": "module",
8
8
  "scripts": {},
9
9
  "dependencies": {
10
- "@ai-sdk/openai": "3.0.49",
11
- "@ai-sdk/xai": "^2.0.64",
12
- "@ai-sdk/anthropic": "^3.0.39",
13
- "@openrouter/ai-sdk-provider": "^2.9.0",
14
- "@composio/core": "^0.10.0",
15
- "@composio/vercel": "^0.9.2",
16
- "agents": "0.8.7",
17
- "ai": "6.0.141",
18
- "isbot": "5.1.32",
19
- "jose": "^6.1.3",
20
- "nanoid": "5.1.6",
21
- "react": "19.2.3",
22
- "react-dom": "19.2.3",
10
+ "@ai-sdk/anthropic": "^4.0.12",
11
+ "@ai-sdk/openai": "4.0.11",
12
+ "@ai-sdk/xai": "^4.0.10",
13
+ "@composio/core": "^0.13.1",
14
+ "@composio/vercel": "^0.11.0",
15
+ "@openrouter/ai-sdk-provider": "^3.0.0",
16
+ "agents": "0.17.3",
17
+ "ai": "7.0.22",
18
+ "isbot": "5.2.0",
19
+ "jose": "^6.2.3",
20
+ "nanoid": "5.1.16",
21
+ "react": "19.2.7",
22
+ "react-dom": "19.2.7",
23
23
  "react-markdown": "^10.1.0",
24
- "react-router": "7.11.0",
24
+ "react-router": "8.2.0",
25
25
  "rehype-highlight": "^7.0.2",
26
26
  "remark-breaks": "^4.0.0",
27
27
  "remark-gfm": "^4.0.1",
28
- "workers-ai-provider": "^2.0.2",
29
- "zod": "^4.2.1",
30
- "zustand": "5.0.9"
28
+ "workers-ai-provider": "^3.3.1",
29
+ "zod": "^4.4.3",
30
+ "zustand": "5.0.14"
31
31
  },
32
32
  "devDependencies": {
33
- "typescript": "5.9.3"
33
+ "typescript": "7.0.2"
34
34
  },
35
35
  "packageManager": "pnpm@10.12.4",
36
36
  "pnpm": {
@@ -1 +0,0 @@
1
- import{tool as o}from"ai";import{z as t}from"zod";var p=(n,i,r,a)=>o({description:"Get the weather in a location (in Celsius)",inputSchema:t.object({location:t.string().describe("The location to get the weather for")}),execute:async({location:e})=>(`${e}`,{location:e,temperature:Math.floor(Math.random()*21)})});export{p as a};
@@ -1 +0,0 @@
1
- var g=Object.create;var e=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=b=>a=>{var c=b[a];if(c)return c();throw new Error("Module not found in bundle: "+a)};var n=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports),o=(b,a)=>{for(var c in a)e(b,c,{get:a[c],enumerable:!0})},l=(b,a,c,f)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of i(a))!k.call(b,d)&&d!==c&&e(b,d,{get:()=>a[d],enumerable:!(f=h(a,d))||f.enumerable});return b};var p=(b,a,c)=>(c=b!=null?g(j(b)):{},l(a||!b||!b.__esModule?e(c,"default",{value:b,enumerable:!0}):c,b));export{m as a,n as b,o as c,p as d};
@@ -1 +0,0 @@
1
- import{a}from"./chunk-43NDF544.js";import"./chunk-U56YWPSI.js";import"./chunk-6BYZCJPP.js";export{a as convertTempMessure};
@@ -1,13 +0,0 @@
1
- import"./chunk-6BYZCJPP.js";var O=44,N=59,x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E=new Uint8Array(64),A=new Uint8Array(128);for(let l=0;l<x.length;l++){let t=x.charCodeAt(l);E[l]=t,A[t]=l}function d(l,t,e){let n=t-e;n=n<0?-n<<1|1:n<<1;do{let i=n&31;n>>>=5,n>0&&(i|=32),l.write(E[i])}while(n>0);return t}var v=1024*16,y=typeof TextDecoder<"u"?new TextDecoder:typeof Buffer<"u"?{decode(l){return Buffer.from(l.buffer,l.byteOffset,l.byteLength).toString()}}:{decode(l){let t="";for(let e=0;e<l.length;e++)t+=String.fromCharCode(l[e]);return t}},j=class{constructor(){this.pos=0,this.out="",this.buffer=new Uint8Array(v)}write(l){let{buffer:t}=this;t[this.pos++]=l,this.pos===v&&(this.out+=y.decode(t),this.pos=0)}flush(){let{buffer:l,out:t,pos:e}=this;return e>0?t+y.decode(l.subarray(0,e)):t}};function L(l){let t=new j,e=0,n=0,i=0,r=0;for(let s=0;s<l.length;s++){let h=l[s];if(s>0&&t.write(N),h.length===0)continue;let o=0;for(let u=0;u<h.length;u++){let a=h[u];u>0&&t.write(O),o=d(t,a[0],o),a.length!==1&&(e=d(t,a[1],e),n=d(t,a[2],n),i=d(t,a[3],i),a.length!==4&&(r=d(t,a[4],r)))}}return t.flush()}var p=class l{constructor(t){this.bits=t instanceof l?t.bits.slice():[]}add(t){this.bits[t>>5]|=1<<(t&31)}has(t){return!!(this.bits[t>>5]&1<<(t&31))}},m=class l{constructor(t,e,n){this.start=t,this.end=e,this.original=n,this.intro="",this.outro="",this.content=n,this.storeName=!1,this.edited=!1,this.previous=null,this.next=null}appendLeft(t){this.outro+=t}appendRight(t){this.intro=this.intro+t}clone(){let t=new l(this.start,this.end,this.original);return t.intro=this.intro,t.outro=this.outro,t.content=this.content,t.storeName=this.storeName,t.edited=this.edited,t}contains(t){return this.start<t&&t<this.end}eachNext(t){let e=this;for(;e;)t(e),e=e.next}eachPrevious(t){let e=this;for(;e;)t(e),e=e.previous}edit(t,e,n){return this.content=t,n||(this.intro="",this.outro=""),this.storeName=e,this.edited=!0,this}prependLeft(t){this.outro=t+this.outro}prependRight(t){this.intro=t+this.intro}reset(){this.intro="",this.outro="",this.edited&&(this.content=this.original,this.storeName=!1,this.edited=!1)}split(t){let e=t-this.start,n=this.original.slice(0,e),i=this.original.slice(e);this.original=n;let r=new l(t,this.end,i);return r.outro=this.outro,this.outro="",this.end=t,this.edited?(r.edit("",!1),this.content=""):this.content=n,r.next=this.next,r.next&&(r.next.previous=r),r.previous=this,this.next=r,r}toString(){return this.intro+this.content+this.outro}trimEnd(t){if(this.outro=this.outro.replace(t,""),this.outro.length)return!0;let e=this.content.replace(t,"");if(e.length)return e!==this.content&&(this.split(this.start+e.length).edit("",void 0,!0),this.edited&&this.edit(e,this.storeName,!0)),!0;if(this.edit("",void 0,!0),this.intro=this.intro.replace(t,""),this.intro.length)return!0}trimStart(t){if(this.intro=this.intro.replace(t,""),this.intro.length)return!0;let e=this.content.replace(t,"");if(e.length){if(e!==this.content){let n=this.split(this.end-e.length);this.edited&&n.edit(e,this.storeName,!0),this.edit("",void 0,!0)}return!0}else if(this.edit("",void 0,!0),this.outro=this.outro.replace(t,""),this.outro.length)return!0}};function $(){return typeof globalThis<"u"&&typeof globalThis.btoa=="function"?l=>globalThis.btoa(unescape(encodeURIComponent(l))):typeof Buffer=="function"?l=>Buffer.from(l,"utf-8").toString("base64"):()=>{throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.")}}var q=$(),w=class{constructor(t){this.version=3,this.file=t.file,this.sources=t.sources,this.sourcesContent=t.sourcesContent,this.names=t.names,this.mappings=L(t.mappings),typeof t.x_google_ignoreList<"u"&&(this.x_google_ignoreList=t.x_google_ignoreList),typeof t.debugId<"u"&&(this.debugId=t.debugId)}toString(){return JSON.stringify(this)}toUrl(){return"data:application/json;charset=utf-8;base64,"+q(this.toString())}};function T(l){let t=l.split(`
2
- `),e=t.filter(r=>/^\t+/.test(r)),n=t.filter(r=>/^ {2,}/.test(r));if(e.length===0&&n.length===0)return null;if(e.length>=n.length)return" ";let i=n.reduce((r,s)=>{let h=/^ +/.exec(s)[0].length;return Math.min(h,r)},1/0);return new Array(i+1).join(" ")}function I(l,t){let e=l.split(/[/\\]/),n=t.split(/[/\\]/);for(e.pop();e[0]===n[0];)e.shift(),n.shift();if(e.length){let i=e.length;for(;i--;)e[i]=".."}return e.concat(n).join("/")}var B=Object.prototype.toString;function _(l){return B.call(l)==="[object Object]"}function S(l){let t=l.split(`
3
- `),e=[];for(let n=0,i=0;n<t.length;n++)e.push(i),i+=t[n].length+1;return function(i){let r=0,s=e.length;for(;r<s;){let u=r+s>>1;i<e[u]?s=u:r=u+1}let h=r-1,o=i-e[h];return{line:h,column:o}}}var U=/\w/,b=class{constructor(t){this.hires=t,this.generatedCodeLine=0,this.generatedCodeColumn=0,this.raw=[],this.rawSegments=this.raw[this.generatedCodeLine]=[],this.pending=null}addEdit(t,e,n,i){if(e.length){let r=e.length-1,s=e.indexOf(`
4
- `,0),h=-1;for(;s>=0&&r>s;){let u=[this.generatedCodeColumn,t,n.line,n.column];i>=0&&u.push(i),this.rawSegments.push(u),this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,h=s,s=e.indexOf(`
5
- `,s+1)}let o=[this.generatedCodeColumn,t,n.line,n.column];i>=0&&o.push(i),this.rawSegments.push(o),this.advance(e.slice(h+1))}else this.pending&&(this.rawSegments.push(this.pending),this.advance(e));this.pending=null}addUneditedChunk(t,e,n,i,r){let s=e.start,h=!0,o=!1;for(;s<e.end;){if(n[s]===`
6
- `)i.line+=1,i.column=0,this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,h=!0,o=!1;else{if(this.hires||h||r.has(s)){let u=[this.generatedCodeColumn,t,i.line,i.column];this.hires==="boundary"?U.test(n[s])?o||(this.rawSegments.push(u),o=!0):(this.rawSegments.push(u),o=!1):this.rawSegments.push(u)}i.column+=1,this.generatedCodeColumn+=1,h=!1}s+=1}this.pending=null}advance(t){if(!t)return;let e=t.split(`
7
- `);if(e.length>1){for(let n=0;n<e.length-1;n++)this.generatedCodeLine++,this.raw[this.generatedCodeLine]=this.rawSegments=[];this.generatedCodeColumn=0}this.generatedCodeColumn+=e[e.length-1].length}},g=`
8
- `,c={insertLeft:!1,insertRight:!1,storeName:!1},C=class l{constructor(t,e={}){let n=new m(0,t.length,t);Object.defineProperties(this,{original:{writable:!0,value:t},outro:{writable:!0,value:""},intro:{writable:!0,value:""},firstChunk:{writable:!0,value:n},lastChunk:{writable:!0,value:n},lastSearchedChunk:{writable:!0,value:n},byStart:{writable:!0,value:{}},byEnd:{writable:!0,value:{}},filename:{writable:!0,value:e.filename},indentExclusionRanges:{writable:!0,value:e.indentExclusionRanges},sourcemapLocations:{writable:!0,value:new p},storedNames:{writable:!0,value:{}},indentStr:{writable:!0,value:void 0},ignoreList:{writable:!0,value:e.ignoreList},offset:{writable:!0,value:e.offset||0}}),this.byStart[0]=n,this.byEnd[t.length]=n}addSourcemapLocation(t){this.sourcemapLocations.add(t)}append(t){if(typeof t!="string")throw new TypeError("outro content must be a string");return this.outro+=t,this}appendLeft(t,e){if(t=t+this.offset,typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byEnd[t];return n?n.appendLeft(e):this.intro+=e,this}appendRight(t,e){if(t=t+this.offset,typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byStart[t];return n?n.appendRight(e):this.outro+=e,this}clone(){let t=new l(this.original,{filename:this.filename,offset:this.offset}),e=this.firstChunk,n=t.firstChunk=t.lastSearchedChunk=e.clone();for(;e;){t.byStart[n.start]=n,t.byEnd[n.end]=n;let i=e.next,r=i&&i.clone();r&&(n.next=r,r.previous=n,n=r),e=i}return t.lastChunk=n,this.indentExclusionRanges&&(t.indentExclusionRanges=this.indentExclusionRanges.slice()),t.sourcemapLocations=new p(this.sourcemapLocations),t.intro=this.intro,t.outro=this.outro,t}generateDecodedMap(t){t=t||{};let e=0,n=Object.keys(this.storedNames),i=new b(t.hires),r=S(this.original);return this.intro&&i.advance(this.intro),this.firstChunk.eachNext(s=>{let h=r(s.start);s.intro.length&&i.advance(s.intro),s.edited?i.addEdit(e,s.content,h,s.storeName?n.indexOf(s.original):-1):i.addUneditedChunk(e,s,this.original,h,this.sourcemapLocations),s.outro.length&&i.advance(s.outro)}),this.outro&&i.advance(this.outro),{file:t.file?t.file.split(/[/\\]/).pop():void 0,sources:[t.source?I(t.file||"",t.source):t.file||""],sourcesContent:t.includeContent?[this.original]:void 0,names:n,mappings:i.raw,x_google_ignoreList:this.ignoreList?[e]:void 0}}generateMap(t){return new w(this.generateDecodedMap(t))}_ensureindentStr(){this.indentStr===void 0&&(this.indentStr=T(this.original))}_getRawIndentString(){return this._ensureindentStr(),this.indentStr}getIndentString(){return this._ensureindentStr(),this.indentStr===null?" ":this.indentStr}indent(t,e){let n=/^[^\r\n]/gm;if(_(t)&&(e=t,t=void 0),t===void 0&&(this._ensureindentStr(),t=this.indentStr||" "),t==="")return this;e=e||{};let i={};e.exclude&&(typeof e.exclude[0]=="number"?[e.exclude]:e.exclude).forEach(a=>{for(let f=a[0];f<a[1];f+=1)i[f]=!0});let r=e.indentStart!==!1,s=u=>r?`${t}${u}`:(r=!0,u);this.intro=this.intro.replace(n,s);let h=0,o=this.firstChunk;for(;o;){let u=o.end;if(o.edited)i[h]||(o.content=o.content.replace(n,s),o.content.length&&(r=o.content[o.content.length-1]===`
9
- `));else for(h=o.start;h<u;){if(!i[h]){let a=this.original[h];a===`
10
- `?r=!0:a!=="\r"&&r&&(r=!1,h===o.start||(this._splitChunk(o,h),o=o.next),o.prependRight(t))}h+=1}h=o.end,o=o.next}return this.outro=this.outro.replace(n,s),this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(t,e){return c.insertLeft||(console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"),c.insertLeft=!0),this.appendLeft(t,e)}insertRight(t,e){return c.insertRight||(console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"),c.insertRight=!0),this.prependRight(t,e)}move(t,e,n){if(t=t+this.offset,e=e+this.offset,n=n+this.offset,n>=t&&n<=e)throw new Error("Cannot move a selection inside itself");this._split(t),this._split(e),this._split(n);let i=this.byStart[t],r=this.byEnd[e],s=i.previous,h=r.next,o=this.byStart[n];if(!o&&r===this.lastChunk)return this;let u=o?o.previous:this.lastChunk;return s&&(s.next=h),h&&(h.previous=s),u&&(u.next=i),o&&(o.previous=r),i.previous||(this.firstChunk=r.next),r.next||(this.lastChunk=i.previous,this.lastChunk.next=null),i.previous=u,r.next=o||null,u||(this.firstChunk=i),o||(this.lastChunk=r),this}overwrite(t,e,n,i){return i=i||{},this.update(t,e,n,{...i,overwrite:!i.contentOnly})}update(t,e,n,i){if(t=t+this.offset,e=e+this.offset,typeof n!="string")throw new TypeError("replacement content must be a string");if(this.original.length!==0){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length}if(e>this.original.length)throw new Error("end is out of bounds");if(t===e)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(t),this._split(e),i===!0&&(c.storeName||(console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"),c.storeName=!0),i={storeName:!0});let r=i!==void 0?i.storeName:!1,s=i!==void 0?i.overwrite:!1;if(r){let u=this.original.slice(t,e);Object.defineProperty(this.storedNames,u,{writable:!0,value:!0,enumerable:!0})}let h=this.byStart[t],o=this.byEnd[e];if(h){let u=h;for(;u!==o;){if(u.next!==this.byStart[u.end])throw new Error("Cannot overwrite across a split point");u=u.next,u.edit("",!1)}h.edit(n,r,!s)}else{let u=new m(t,e,"").edit(n,r);o.next=u,u.previous=o}return this}prepend(t){if(typeof t!="string")throw new TypeError("outro content must be a string");return this.intro=t+this.intro,this}prependLeft(t,e){if(t=t+this.offset,typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byEnd[t];return n?n.prependLeft(e):this.intro=e+this.intro,this}prependRight(t,e){if(t=t+this.offset,typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byStart[t];return n?n.prependRight(e):this.outro=e+this.outro,this}remove(t,e){if(t=t+this.offset,e=e+this.offset,this.original.length!==0){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length}if(t===e)return this;if(t<0||e>this.original.length)throw new Error("Character is out of bounds");if(t>e)throw new Error("end must be greater than start");this._split(t),this._split(e);let n=this.byStart[t];for(;n;)n.intro="",n.outro="",n.edit(""),n=e>n.end?this.byStart[n.end]:null;return this}reset(t,e){if(t=t+this.offset,e=e+this.offset,this.original.length!==0){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length}if(t===e)return this;if(t<0||e>this.original.length)throw new Error("Character is out of bounds");if(t>e)throw new Error("end must be greater than start");this._split(t),this._split(e);let n=this.byStart[t];for(;n;)n.reset(),n=e>n.end?this.byStart[n.end]:null;return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let t=this.lastChunk;do{if(t.outro.length)return t.outro[t.outro.length-1];if(t.content.length)return t.content[t.content.length-1];if(t.intro.length)return t.intro[t.intro.length-1]}while(t=t.previous);return this.intro.length?this.intro[this.intro.length-1]:""}lastLine(){let t=this.outro.lastIndexOf(g);if(t!==-1)return this.outro.substr(t+1);let e=this.outro,n=this.lastChunk;do{if(n.outro.length>0){if(t=n.outro.lastIndexOf(g),t!==-1)return n.outro.substr(t+1)+e;e=n.outro+e}if(n.content.length>0){if(t=n.content.lastIndexOf(g),t!==-1)return n.content.substr(t+1)+e;e=n.content+e}if(n.intro.length>0){if(t=n.intro.lastIndexOf(g),t!==-1)return n.intro.substr(t+1)+e;e=n.intro+e}}while(n=n.previous);return t=this.intro.lastIndexOf(g),t!==-1?this.intro.substr(t+1)+e:this.intro+e}slice(t=0,e=this.original.length-this.offset){if(t=t+this.offset,e=e+this.offset,this.original.length!==0){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length}let n="",i=this.firstChunk;for(;i&&(i.start>t||i.end<=t);){if(i.start<e&&i.end>=e)return n;i=i.next}if(i&&i.edited&&i.start!==t)throw new Error(`Cannot use replaced character ${t} as slice start anchor.`);let r=i;for(;i;){i.intro&&(r!==i||i.start===t)&&(n+=i.intro);let s=i.start<e&&i.end>=e;if(s&&i.edited&&i.end!==e)throw new Error(`Cannot use replaced character ${e} as slice end anchor.`);let h=r===i?t-i.start:0,o=s?i.content.length+e-i.end:i.content.length;if(n+=i.content.slice(h,o),i.outro&&(!s||i.end===e)&&(n+=i.outro),s)break;i=i.next}return n}snip(t,e){let n=this.clone();return n.remove(0,t),n.remove(e,n.original.length),n}_split(t){if(this.byStart[t]||this.byEnd[t])return;let e=this.lastSearchedChunk,n=e,i=t>e.end;for(;e;){if(e.contains(t))return this._splitChunk(e,t);if(e=i?this.byStart[e.end]:this.byEnd[e.start],e===n)return;n=e}}_splitChunk(t,e){if(t.edited&&t.content.length){let i=S(this.original)(e);throw new Error(`Cannot split a chunk that has already been edited (${i.line}:${i.column} \u2013 "${t.original}")`)}let n=t.split(e);return this.byEnd[e]=t,this.byStart[e]=n,this.byEnd[n.end]=n,t===this.lastChunk&&(this.lastChunk=n),this.lastSearchedChunk=t,!0}toString(){let t=this.intro,e=this.firstChunk;for(;e;)t+=e.toString(),e=e.next;return t+this.outro}isEmpty(){let t=this.firstChunk;do if(t.intro.length&&t.intro.trim()||t.content.length&&t.content.trim()||t.outro.length&&t.outro.trim())return!1;while(t=t.next);return!0}length(){let t=this.firstChunk,e=0;do e+=t.intro.length+t.content.length+t.outro.length;while(t=t.next);return e}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimEndAborted(t){let e=new RegExp((t||"\\s")+"+$");if(this.outro=this.outro.replace(e,""),this.outro.length)return!0;let n=this.lastChunk;do{let i=n.end,r=n.trimEnd(e);if(n.end!==i&&(this.lastChunk===n&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return!0;n=n.previous}while(n);return!1}trimEnd(t){return this.trimEndAborted(t),this}trimStartAborted(t){let e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),this.intro.length)return!0;let n=this.firstChunk;do{let i=n.end,r=n.trimStart(e);if(n.end!==i&&(n===this.lastChunk&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return!0;n=n.next}while(n);return!1}trimStart(t){return this.trimStartAborted(t),this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(t,e){function n(r,s){return typeof e=="string"?e.replace(/\$(\$|&|\d+)/g,(h,o)=>o==="$"?"$":o==="&"?r[0]:+o<r.length?r[+o]:`$${o}`):e(...r,r.index,s,r.groups)}function i(r,s){let h,o=[];for(;h=r.exec(s);)o.push(h);return o}if(t.global)i(t,this.original).forEach(s=>{if(s.index!=null){let h=n(s,this.original);h!==s[0]&&this.overwrite(s.index,s.index+s[0].length,h)}});else{let r=this.original.match(t);if(r&&r.index!=null){let s=n(r,this.original);s!==r[0]&&this.overwrite(r.index,r.index+r[0].length,s)}}return this}_replaceString(t,e){let{original:n}=this,i=n.indexOf(t);return i!==-1&&(typeof e=="function"&&(e=e(t,i,n)),t!==e&&this.overwrite(i,i+t.length,e)),this}replace(t,e){return typeof t=="string"?this._replaceString(t,e):this._replaceRegexp(t,e)}_replaceAllString(t,e){let{original:n}=this,i=t.length;for(let r=n.indexOf(t);r!==-1;r=n.indexOf(t,r+i)){let s=n.slice(r,r+i),h=e;typeof e=="function"&&(h=e(s,r,n)),s!==h&&this.overwrite(r,r+i,h)}return this}replaceAll(t,e){if(typeof t=="string")return this._replaceAllString(t,e);if(!t.global)throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");return this._replaceRegexp(t,e)}},k=Object.prototype.hasOwnProperty,R=class l{constructor(t={}){this.intro=t.intro||"",this.separator=t.separator!==void 0?t.separator:`
11
- `,this.sources=[],this.uniqueSources=[],this.uniqueSourceIndexByFilename={}}addSource(t){if(t instanceof C)return this.addSource({content:t,filename:t.filename,separator:this.separator});if(!_(t)||!t.content)throw new Error("bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`");if(["filename","ignoreList","indentExclusionRanges","separator"].forEach(e=>{k.call(t,e)||(t[e]=t.content[e])}),t.separator===void 0&&(t.separator=this.separator),t.filename)if(!k.call(this.uniqueSourceIndexByFilename,t.filename))this.uniqueSourceIndexByFilename[t.filename]=this.uniqueSources.length,this.uniqueSources.push({filename:t.filename,content:t.content.original});else{let e=this.uniqueSources[this.uniqueSourceIndexByFilename[t.filename]];if(t.content.original!==e.content)throw new Error(`Illegal source: same filename (${t.filename}), different contents`)}return this.sources.push(t),this}append(t,e){return this.addSource({content:new C(t),separator:e&&e.separator||""}),this}clone(){let t=new l({intro:this.intro,separator:this.separator});return this.sources.forEach(e=>{t.addSource({filename:e.filename,content:e.content.clone(),separator:e.separator})}),t}generateDecodedMap(t={}){let e=[],n;this.sources.forEach(r=>{Object.keys(r.content.storedNames).forEach(s=>{~e.indexOf(s)||e.push(s)})});let i=new b(t.hires);return this.intro&&i.advance(this.intro),this.sources.forEach((r,s)=>{s>0&&i.advance(this.separator);let h=r.filename?this.uniqueSourceIndexByFilename[r.filename]:-1,o=r.content,u=S(o.original);o.intro&&i.advance(o.intro),o.firstChunk.eachNext(a=>{let f=u(a.start);a.intro.length&&i.advance(a.intro),r.filename?a.edited?i.addEdit(h,a.content,f,a.storeName?e.indexOf(a.original):-1):i.addUneditedChunk(h,a,o.original,f,o.sourcemapLocations):i.advance(a.content),a.outro.length&&i.advance(a.outro)}),o.outro&&i.advance(o.outro),r.ignoreList&&h!==-1&&(n===void 0&&(n=[]),n.push(h))}),{file:t.file?t.file.split(/[/\\]/).pop():void 0,sources:this.uniqueSources.map(r=>t.file?I(t.file,r.filename):r.filename),sourcesContent:this.uniqueSources.map(r=>t.includeContent?r.content:null),names:e,mappings:i.raw,x_google_ignoreList:n}}generateMap(t){return new w(this.generateDecodedMap(t))}getIndentString(){let t={};return this.sources.forEach(e=>{let n=e.content._getRawIndentString();n!==null&&(t[n]||(t[n]=0),t[n]+=1)}),Object.keys(t).sort((e,n)=>t[e]-t[n])[0]||" "}indent(t){if(arguments.length||(t=this.getIndentString()),t==="")return this;let e=!this.intro||this.intro.slice(-1)===`
12
- `;return this.sources.forEach((n,i)=>{let r=n.separator!==void 0?n.separator:this.separator,s=e||i>0&&/\r?\n$/.test(r);n.content.indent(t,{exclude:n.indentExclusionRanges,indentStart:s}),e=n.content.lastChar()===`
13
- `}),this.intro&&(this.intro=t+this.intro.replace(/^[^\n]/gm,(n,i)=>i>0?t+n:n)),this}prepend(t){return this.intro=t+this.intro,this}toString(){let t=this.sources.map((e,n)=>{let i=e.separator!==void 0?e.separator:this.separator;return(n>0?i:"")+e.content.toString()}).join("");return this.intro+t}isEmpty(){return!(this.intro.length&&this.intro.trim()||this.sources.some(t=>!t.content.isEmpty()))}length(){return this.sources.reduce((t,e)=>t+e.content.length(),this.intro.length)}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimStart(t){let e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),!this.intro){let n,i=0;do if(n=this.sources[i++],!n)break;while(!n.content.trimStartAborted(t))}return this}trimEnd(t){let e=new RegExp((t||"\\s")+"+$"),n,i=this.sources.length-1;do if(n=this.sources[i--],!n){this.intro=this.intro.replace(e,"");break}while(!n.content.trimEndAborted(t));return this}};export{R as Bundle,w as SourceMap,C as default};