@adaptive-ai/sdk 0.1.28 → 0.1.30
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.
- package/dist/server/index.d.ts +220 -11
- package/dist/server/index.js +26 -2
- package/package.json +6 -1
package/dist/server/index.d.ts
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
import * as _trpc_client from '@trpc/client';
|
|
4
4
|
import * as _trpc_server from '@trpc/server';
|
|
5
5
|
import * as _trpc_server_rpc from '@trpc/server/rpc';
|
|
6
|
+
import * as plainjob from 'plainjob';
|
|
7
|
+
import { Job, JobStatus } from 'plainjob';
|
|
6
8
|
import superjson from 'superjson';
|
|
9
|
+
import { handleRpc } from 'typed-rpc/server';
|
|
7
10
|
|
|
8
11
|
declare const ProductKind: {
|
|
9
12
|
readonly SUBSCRIPTION: "SUBSCRIPTION";
|
|
@@ -1641,6 +1644,63 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1641
1644
|
stopAt?: string | undefined;
|
|
1642
1645
|
maxExecutions?: number | undefined;
|
|
1643
1646
|
}>, "many">;
|
|
1647
|
+
events: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
1648
|
+
provider: z.ZodNativeEnum<{
|
|
1649
|
+
readonly AC1: "AC1";
|
|
1650
|
+
readonly GITHUB_USER: "GITHUB_USER";
|
|
1651
|
+
readonly GITHUB_BOT: "GITHUB_BOT";
|
|
1652
|
+
readonly GOOGLE: "GOOGLE";
|
|
1653
|
+
readonly SLACK: "SLACK";
|
|
1654
|
+
readonly SLACK_BOT: "SLACK_BOT";
|
|
1655
|
+
readonly DISCORD: "DISCORD";
|
|
1656
|
+
readonly NOTION: "NOTION";
|
|
1657
|
+
readonly TWITTER: "TWITTER";
|
|
1658
|
+
readonly LINKEDIN: "LINKEDIN";
|
|
1659
|
+
readonly YAHOO: "YAHOO";
|
|
1660
|
+
readonly FIGMA: "FIGMA";
|
|
1661
|
+
readonly PLAID: "PLAID";
|
|
1662
|
+
readonly SQUARE: "SQUARE";
|
|
1663
|
+
readonly SHOPIFY: "SHOPIFY";
|
|
1664
|
+
readonly WHOOP: "WHOOP";
|
|
1665
|
+
}>;
|
|
1666
|
+
event: z.ZodString;
|
|
1667
|
+
handler: z.ZodEffects<z.ZodString, string, string>;
|
|
1668
|
+
}, "strip", z.ZodTypeAny, {
|
|
1669
|
+
event: string;
|
|
1670
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1671
|
+
handler: string;
|
|
1672
|
+
}, {
|
|
1673
|
+
event: string;
|
|
1674
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1675
|
+
handler: string;
|
|
1676
|
+
}>, "many">>;
|
|
1677
|
+
webhooks: z.ZodDefault<z.ZodArray<z.ZodObject<{
|
|
1678
|
+
handler: z.ZodEffects<z.ZodString, string, string>;
|
|
1679
|
+
provider: z.ZodOptional<z.ZodNullable<z.ZodNativeEnum<{
|
|
1680
|
+
readonly AC1: "AC1";
|
|
1681
|
+
readonly GITHUB_USER: "GITHUB_USER";
|
|
1682
|
+
readonly GITHUB_BOT: "GITHUB_BOT";
|
|
1683
|
+
readonly GOOGLE: "GOOGLE";
|
|
1684
|
+
readonly SLACK: "SLACK";
|
|
1685
|
+
readonly SLACK_BOT: "SLACK_BOT";
|
|
1686
|
+
readonly DISCORD: "DISCORD";
|
|
1687
|
+
readonly NOTION: "NOTION";
|
|
1688
|
+
readonly TWITTER: "TWITTER";
|
|
1689
|
+
readonly LINKEDIN: "LINKEDIN";
|
|
1690
|
+
readonly YAHOO: "YAHOO";
|
|
1691
|
+
readonly FIGMA: "FIGMA";
|
|
1692
|
+
readonly PLAID: "PLAID";
|
|
1693
|
+
readonly SQUARE: "SQUARE";
|
|
1694
|
+
readonly SHOPIFY: "SHOPIFY";
|
|
1695
|
+
readonly WHOOP: "WHOOP";
|
|
1696
|
+
}>>>;
|
|
1697
|
+
}, "strip", z.ZodTypeAny, {
|
|
1698
|
+
handler: string;
|
|
1699
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1700
|
+
}, {
|
|
1701
|
+
handler: string;
|
|
1702
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1703
|
+
}>, "many">>;
|
|
1644
1704
|
}, "strip", z.ZodTypeAny, {
|
|
1645
1705
|
crons: {
|
|
1646
1706
|
slug: string;
|
|
@@ -1653,6 +1713,15 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1653
1713
|
stopAt?: string | undefined;
|
|
1654
1714
|
maxExecutions?: number | undefined;
|
|
1655
1715
|
}[];
|
|
1716
|
+
events: {
|
|
1717
|
+
event: string;
|
|
1718
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1719
|
+
handler: string;
|
|
1720
|
+
}[];
|
|
1721
|
+
webhooks: {
|
|
1722
|
+
handler: string;
|
|
1723
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1724
|
+
}[];
|
|
1656
1725
|
}, {
|
|
1657
1726
|
crons: {
|
|
1658
1727
|
slug: string;
|
|
@@ -1665,6 +1734,15 @@ export declare const appConfigSchema: z.ZodObject<{
|
|
|
1665
1734
|
stopAt?: string | undefined;
|
|
1666
1735
|
maxExecutions?: number | undefined;
|
|
1667
1736
|
}[];
|
|
1737
|
+
events?: {
|
|
1738
|
+
event: string;
|
|
1739
|
+
provider: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1";
|
|
1740
|
+
handler: string;
|
|
1741
|
+
}[] | undefined;
|
|
1742
|
+
webhooks?: {
|
|
1743
|
+
handler: string;
|
|
1744
|
+
provider?: "GITHUB_USER" | "GITHUB_BOT" | "GOOGLE" | "SLACK" | "SLACK_BOT" | "DISCORD" | "NOTION" | "TWITTER" | "LINKEDIN" | "YAHOO" | "FIGMA" | "PLAID" | "SQUARE" | "SHOPIFY" | "WHOOP" | "AC1" | null | undefined;
|
|
1745
|
+
}[] | undefined;
|
|
1668
1746
|
}>;
|
|
1669
1747
|
export type AppConfig = z.infer<typeof appConfigSchema>;
|
|
1670
1748
|
declare const AuthProvider: {
|
|
@@ -1686,6 +1764,80 @@ declare const AuthProvider: {
|
|
|
1686
1764
|
readonly WHOOP: "WHOOP";
|
|
1687
1765
|
};
|
|
1688
1766
|
export type AuthProvider = (typeof AuthProvider)[keyof typeof AuthProvider];
|
|
1767
|
+
export type ErrorLogSource = "server" | "client" | "worker";
|
|
1768
|
+
export type ErrorLogEntry = {
|
|
1769
|
+
source: ErrorLogSource;
|
|
1770
|
+
message: string;
|
|
1771
|
+
stack?: string;
|
|
1772
|
+
metadata?: object;
|
|
1773
|
+
requestId?: string;
|
|
1774
|
+
};
|
|
1775
|
+
export type ErrorTracker = ReturnType<typeof createErrorTracker>;
|
|
1776
|
+
declare function createErrorTracker({ environment, dbPath, }: {
|
|
1777
|
+
environment: string;
|
|
1778
|
+
dbPath?: string;
|
|
1779
|
+
}): {
|
|
1780
|
+
captureClientLog: ({ body, requestId, }: {
|
|
1781
|
+
body: string;
|
|
1782
|
+
requestId?: string;
|
|
1783
|
+
}) => {
|
|
1784
|
+
message: string;
|
|
1785
|
+
persisted: boolean;
|
|
1786
|
+
};
|
|
1787
|
+
captureRpcError: ({ result, requestId, }: {
|
|
1788
|
+
result: unknown;
|
|
1789
|
+
requestId?: string;
|
|
1790
|
+
}) => boolean;
|
|
1791
|
+
getRecentErrors: (limit?: number) => unknown[];
|
|
1792
|
+
hasErrors: (sinceMinutes?: number) => boolean;
|
|
1793
|
+
logError: (entry: ErrorLogEntry) => void;
|
|
1794
|
+
registerProcessHandlers: ({ logger, }?: {
|
|
1795
|
+
logger?: Pick<Console, "error">;
|
|
1796
|
+
}) => void;
|
|
1797
|
+
};
|
|
1798
|
+
export type QueueLogger = {
|
|
1799
|
+
error: (...args: unknown[]) => void;
|
|
1800
|
+
warn: (...args: unknown[]) => void;
|
|
1801
|
+
info: (...args: unknown[]) => void;
|
|
1802
|
+
debug: (...args: unknown[]) => void;
|
|
1803
|
+
};
|
|
1804
|
+
export type QueueHandlers = Record<string, (payload: any, job: Job) => Promise<void>> & {
|
|
1805
|
+
getJob?: never;
|
|
1806
|
+
};
|
|
1807
|
+
export type QueueApi<THandlers extends QueueHandlers> = {
|
|
1808
|
+
[K in keyof THandlers]: (payload: Parameters<THandlers[K]>[0]) => {
|
|
1809
|
+
id: number;
|
|
1810
|
+
};
|
|
1811
|
+
};
|
|
1812
|
+
declare function createQueue<THandlers extends QueueHandlers>({ dbPath, handlers, errorTracker, queueName, logger, }: {
|
|
1813
|
+
dbPath: string;
|
|
1814
|
+
handlers: THandlers;
|
|
1815
|
+
errorTracker?: Pick<ErrorTracker, "logError">;
|
|
1816
|
+
queueName?: string;
|
|
1817
|
+
logger?: QueueLogger;
|
|
1818
|
+
}): {
|
|
1819
|
+
getActiveJobCount: () => number;
|
|
1820
|
+
getJob: (id: number) => {
|
|
1821
|
+
id: number;
|
|
1822
|
+
type: string;
|
|
1823
|
+
data: string;
|
|
1824
|
+
status: JobStatus;
|
|
1825
|
+
createdAt: number;
|
|
1826
|
+
nextRunAt?: number;
|
|
1827
|
+
failedAt?: number;
|
|
1828
|
+
error?: string;
|
|
1829
|
+
} | undefined;
|
|
1830
|
+
getJobCounts: () => {
|
|
1831
|
+
pending: number;
|
|
1832
|
+
processing: number;
|
|
1833
|
+
done: number;
|
|
1834
|
+
failed: number;
|
|
1835
|
+
};
|
|
1836
|
+
getPendingJobCount: () => number;
|
|
1837
|
+
queue: QueueApi<THandlers>;
|
|
1838
|
+
startWorker: () => plainjob.Worker;
|
|
1839
|
+
};
|
|
1840
|
+
export type QueueController<THandlers extends QueueHandlers> = ReturnType<typeof createQueue<THandlers>>;
|
|
1689
1841
|
export type SignInInput = {
|
|
1690
1842
|
email: string;
|
|
1691
1843
|
phoneNumber?: null | undefined;
|
|
@@ -2248,15 +2400,15 @@ declare let client: {
|
|
|
2248
2400
|
};
|
|
2249
2401
|
_input_in: {
|
|
2250
2402
|
name: string;
|
|
2251
|
-
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2252
2403
|
description: string;
|
|
2404
|
+
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2253
2405
|
price: number;
|
|
2254
2406
|
appId?: string | undefined;
|
|
2255
2407
|
};
|
|
2256
2408
|
_input_out: {
|
|
2257
2409
|
name: string;
|
|
2258
|
-
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2259
2410
|
description: string;
|
|
2411
|
+
kind: "IN_APP_PURCHASE" | "SUBSCRIPTION";
|
|
2260
2412
|
price: number;
|
|
2261
2413
|
appId?: string | undefined;
|
|
2262
2414
|
};
|
|
@@ -2266,8 +2418,8 @@ declare let client: {
|
|
|
2266
2418
|
purchaseLink: string;
|
|
2267
2419
|
id: string;
|
|
2268
2420
|
name: string;
|
|
2269
|
-
kind: ProductKind;
|
|
2270
2421
|
description: string;
|
|
2422
|
+
kind: ProductKind;
|
|
2271
2423
|
price: number;
|
|
2272
2424
|
}>>;
|
|
2273
2425
|
};
|
|
@@ -2357,8 +2509,8 @@ declare let client: {
|
|
|
2357
2509
|
purchaseLink: string;
|
|
2358
2510
|
id: string;
|
|
2359
2511
|
name: string;
|
|
2360
|
-
kind: ProductKind;
|
|
2361
2512
|
description: string;
|
|
2513
|
+
kind: ProductKind;
|
|
2362
2514
|
price: number;
|
|
2363
2515
|
}[]>>;
|
|
2364
2516
|
};
|
|
@@ -2449,8 +2601,8 @@ declare let client: {
|
|
|
2449
2601
|
}, {
|
|
2450
2602
|
id: string;
|
|
2451
2603
|
name: string;
|
|
2452
|
-
kind: ProductKind;
|
|
2453
2604
|
description: string;
|
|
2605
|
+
kind: ProductKind;
|
|
2454
2606
|
price: number;
|
|
2455
2607
|
}[]>>;
|
|
2456
2608
|
};
|
|
@@ -2729,14 +2881,14 @@ declare let client: {
|
|
|
2729
2881
|
pushToken: string | null | undefined;
|
|
2730
2882
|
};
|
|
2731
2883
|
_input_in: {
|
|
2732
|
-
userId: string;
|
|
2733
2884
|
provider: string;
|
|
2885
|
+
userId: string;
|
|
2734
2886
|
scope: string;
|
|
2735
2887
|
appId?: string | undefined;
|
|
2736
2888
|
};
|
|
2737
2889
|
_input_out: {
|
|
2738
|
-
userId: string;
|
|
2739
2890
|
provider: string;
|
|
2891
|
+
userId: string;
|
|
2740
2892
|
scope: string;
|
|
2741
2893
|
appId?: string | undefined;
|
|
2742
2894
|
};
|
|
@@ -3005,15 +3157,15 @@ declare let client: {
|
|
|
3005
3157
|
pushToken: string | null | undefined;
|
|
3006
3158
|
};
|
|
3007
3159
|
_input_in: {
|
|
3008
|
-
connectionToken: string;
|
|
3009
3160
|
url: string;
|
|
3161
|
+
connectionToken: string;
|
|
3010
3162
|
method: string;
|
|
3011
3163
|
body?: any;
|
|
3012
3164
|
headers?: Record<string, string> | undefined;
|
|
3013
3165
|
};
|
|
3014
3166
|
_input_out: {
|
|
3015
|
-
connectionToken: string;
|
|
3016
3167
|
url: string;
|
|
3168
|
+
connectionToken: string;
|
|
3017
3169
|
method: string;
|
|
3018
3170
|
body?: any;
|
|
3019
3171
|
headers?: Record<string, string> | undefined;
|
|
@@ -3298,11 +3450,64 @@ declare let client: {
|
|
|
3298
3450
|
}, string>>;
|
|
3299
3451
|
};
|
|
3300
3452
|
};
|
|
3301
|
-
export
|
|
3453
|
+
export type InitializeServerEnvironmentInput = {
|
|
3302
3454
|
baseUrl: string;
|
|
3303
3455
|
realtimeDomain: string;
|
|
3304
3456
|
guestServicesUrl: string;
|
|
3305
|
-
|
|
3457
|
+
environment: string;
|
|
3458
|
+
queueDbPath?: string;
|
|
3459
|
+
errorsDbPath?: string;
|
|
3460
|
+
};
|
|
3461
|
+
export type InitializedServerEnvironment<THandlers extends QueueHandlers = QueueHandlers> = {
|
|
3462
|
+
environment: string;
|
|
3463
|
+
queueDbPath?: string;
|
|
3464
|
+
errorsDbPath?: string;
|
|
3465
|
+
errorTracker?: ErrorTracker;
|
|
3466
|
+
queue?: QueueController<THandlers>;
|
|
3467
|
+
queueWorkerStarted?: boolean;
|
|
3468
|
+
};
|
|
3469
|
+
export type HonoLikeContext<TRequestBody = unknown, TJsonResponse extends Response = Response> = {
|
|
3470
|
+
req: {
|
|
3471
|
+
json(): Promise<TRequestBody>;
|
|
3472
|
+
text(): Promise<string>;
|
|
3473
|
+
header(name: string): string | undefined;
|
|
3474
|
+
method: string;
|
|
3475
|
+
url: string;
|
|
3476
|
+
};
|
|
3477
|
+
json(data: unknown): TJsonResponse;
|
|
3478
|
+
};
|
|
3479
|
+
export type HonoRpcOptions = NonNullable<Parameters<typeof handleRpc>[2]>;
|
|
3480
|
+
export type HonoMiddlewareNext = () => Promise<void>;
|
|
3481
|
+
export type HonoMiddlewareHandler<TContext extends HonoLikeContext = HonoLikeContext> = (context: TContext, next: HonoMiddlewareNext) => Promise<Response | void>;
|
|
3482
|
+
export declare function initializeServerEnvironment<THandlers extends QueueHandlers>({ baseUrl, realtimeDomain, guestServicesUrl, environment, queueDbPath, errorsDbPath, }: InitializeServerEnvironmentInput): InitializedServerEnvironment<THandlers>;
|
|
3483
|
+
export declare function getErrorTracker(): {
|
|
3484
|
+
captureClientLog: ({ body, requestId, }: {
|
|
3485
|
+
body: string;
|
|
3486
|
+
requestId?: string;
|
|
3487
|
+
}) => {
|
|
3488
|
+
message: string;
|
|
3489
|
+
persisted: boolean;
|
|
3490
|
+
};
|
|
3491
|
+
captureRpcError: ({ result, requestId, }: {
|
|
3492
|
+
result: unknown;
|
|
3493
|
+
requestId?: string;
|
|
3494
|
+
}) => boolean;
|
|
3495
|
+
getRecentErrors: (limit?: number) => unknown[];
|
|
3496
|
+
hasErrors: (sinceMinutes?: number) => boolean;
|
|
3497
|
+
logError: (entry: ErrorLogEntry) => void;
|
|
3498
|
+
registerProcessHandlers: ({ logger, }?: {
|
|
3499
|
+
logger?: Pick<Console, "error">;
|
|
3500
|
+
}) => void;
|
|
3501
|
+
};
|
|
3502
|
+
export declare function getQueue<THandlers extends QueueHandlers = QueueHandlers>(): NonNullable<InitializedServerEnvironment<THandlers>["queue"]>["queue"] & Pick<QueueController<THandlers>, "getJob">;
|
|
3503
|
+
export declare function honoMiddleware<THandlers extends QueueHandlers, TProcedures extends Parameters<typeof handleRpc>[1], TContext extends HonoLikeContext = HonoLikeContext>({ procedures, jobs, transcoder, rpcPath, loggerPath, queueStatusPath, }: {
|
|
3504
|
+
procedures: TProcedures;
|
|
3505
|
+
jobs?: THandlers;
|
|
3506
|
+
transcoder?: HonoRpcOptions["transcoder"];
|
|
3507
|
+
rpcPath?: string;
|
|
3508
|
+
loggerPath?: string | false;
|
|
3509
|
+
queueStatusPath?: string | false;
|
|
3510
|
+
}): HonoMiddlewareHandler<TContext>;
|
|
3306
3511
|
export type MutationProxy<TClient> = {
|
|
3307
3512
|
[K in keyof TClient as TClient[K] extends {
|
|
3308
3513
|
mutate: (...args: any) => any;
|
|
@@ -3361,4 +3566,8 @@ declare namespace z {
|
|
|
3361
3566
|
export { AnyZodObject, AnyZodTuple, ArrayCardinality, ArrayKeys, AssertArray, AsyncParseReturnType, BRAND, CatchallInput, CatchallOutput, CustomErrorParams, DIRTY, DenormalizedError, EMPTY_PATH, Effect, EnumLike, EnumValues, ErrorMapCtx, FilterEnum, INVALID, Indices, InnerTypeOfFunction, InputTypeOfTuple, InputTypeOfTupleWithRest, IpVersion, IssueData, KeySchema, NEVER, OK, ObjectPair, OuterTypeOfFunction, OutputTypeOfTuple, OutputTypeOfTupleWithRest, ParseContext, ParseInput, ParseParams, ParsePath, ParsePathComponent, ParseResult, ParseReturnType, ParseStatus, PassthroughType, PreprocessEffect, Primitive, ProcessedCreateParams, RawCreateParams, RecordType, Refinement, RefinementCtx, RefinementEffect, SafeParseError, SafeParseReturnType, SafeParseSuccess, Scalars, SomeZodObject, StringValidation, SuperRefinement, SyncParseReturnType, TransformEffect, TypeOf, TypeOf as infer, UnknownKeysParam, Values, Writeable, ZodAny, ZodAnyDef, ZodArray, ZodArrayDef, ZodBigInt, ZodBigIntCheck, ZodBigIntDef, ZodBoolean, ZodBooleanDef, ZodBranded, ZodBrandedDef, ZodCatch, ZodCatchDef, ZodCustomIssue, ZodDate, ZodDateCheck, ZodDateDef, ZodDefault, ZodDefaultDef, ZodDiscriminatedUnion, ZodDiscriminatedUnionDef, ZodDiscriminatedUnionOption, ZodEffects, ZodEffects as ZodTransformer, ZodEffectsDef, ZodEnum, ZodEnumDef, ZodError, ZodErrorMap, ZodFirstPartySchemaTypes, ZodFirstPartyTypeKind, ZodFormattedError, ZodFunction, ZodFunctionDef, ZodIntersection, ZodIntersectionDef, ZodInvalidArgumentsIssue, ZodInvalidDateIssue, ZodInvalidEnumValueIssue, ZodInvalidIntersectionTypesIssue, ZodInvalidLiteralIssue, ZodInvalidReturnTypeIssue, ZodInvalidStringIssue, ZodInvalidTypeIssue, ZodInvalidUnionDiscriminatorIssue, ZodInvalidUnionIssue, ZodIssue, ZodIssueBase, ZodIssueCode, ZodIssueOptionalMessage, ZodLazy, ZodLazyDef, ZodLiteral, ZodLiteralDef, ZodMap, ZodMapDef, ZodNaN, ZodNaNDef, ZodNativeEnum, ZodNativeEnumDef, ZodNever, ZodNeverDef, ZodNonEmptyArray, ZodNotFiniteIssue, ZodNotMultipleOfIssue, ZodNull, ZodNullDef, ZodNullable, ZodNullableDef, ZodNullableType, ZodNumber, ZodNumberCheck, ZodNumberDef, ZodObject, ZodObjectDef, ZodOptional, ZodOptionalDef, ZodOptionalType, ZodParsedType, ZodPipeline, ZodPipelineDef, ZodPromise, ZodPromiseDef, ZodRawShape, ZodReadonly, ZodReadonlyDef, ZodRecord, ZodRecordDef, ZodSet, ZodSetDef, ZodString, ZodStringCheck, ZodStringDef, ZodSymbol, ZodSymbolDef, ZodTooBigIssue, ZodTooSmallIssue, ZodTuple, ZodTupleDef, ZodTupleItems, ZodType, ZodType as Schema, ZodType as ZodSchema, ZodTypeAny, ZodTypeDef, ZodUndefined, ZodUndefinedDef, ZodUnion, ZodUnionDef, ZodUnionOptions, ZodUnknown, ZodUnknownDef, ZodUnrecognizedKeysIssue, ZodVoid, ZodVoidDef, addIssueToContext, anyType as any, arrayOutputType, arrayType as array, baseObjectInputType, baseObjectOutputType, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, deoptional, discriminatedUnionType as discriminatedUnion, effectsType as effect, effectsType as transformer, enumType as enum, errorMap as defaultErrorMap, functionType as function, getErrorMap, getParsedType, inferFlattenedErrors, inferFormattedError, input, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, mergeTypes, nanType as nan, nativeEnumType as nativeEnum, neverType as never, noUnrecognized, nullType as null, nullableType as nullable, numberType as number, objectInputType, objectOutputType, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, output, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setErrorMap, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, tupleType as tuple, typeToFlattenedError, typecast, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void };
|
|
3362
3567
|
}
|
|
3363
3568
|
|
|
3569
|
+
export {
|
|
3570
|
+
Job,
|
|
3571
|
+
};
|
|
3572
|
+
|
|
3364
3573
|
export {};
|
package/dist/server/index.js
CHANGED
|
@@ -1,2 +1,26 @@
|
|
|
1
|
-
import {z
|
|
2
|
-
|
|
1
|
+
import {z}from'zod';import {createTRPCProxyClient,httpLink}from'@trpc/client';import {AsyncLocalStorage}from'async_hooks';import x from'superjson';import {handleRpc}from'typed-rpc/server';import {inspect}from'util';import Ce from'better-sqlite3';import {better,defineQueue,defineWorker,JobStatus}from'plainjob';var le={GITHUB_USER:"GITHUB_USER",GITHUB_BOT:"GITHUB_BOT",GOOGLE:"GOOGLE",SLACK:"SLACK",SLACK_BOT:"SLACK_BOT",DISCORD:"DISCORD",NOTION:"NOTION",TWITTER:"TWITTER",LINKEDIN:"LINKEDIN",YAHOO:"YAHOO",FIGMA:"FIGMA",PLAID:"PLAID",SQUARE:"SQUARE",SHOPIFY:"SHOPIFY",WHOOP:"WHOOP"},C={...le,AC1:"AC1"};var pe=z.object({slug:z.string(),name:z.string().optional(),schedule:z.string(),description:z.string().optional(),rpcEndpoint:z.string(),isEnabled:z.boolean().default(true),stopAt:z.string().datetime().optional(),maxExecutions:z.number().optional(),timezone:z.string().optional()}),$=z.string().refine(e=>/^[a-zA-Z0-9_]+$/.test(e),"Must be a valid identifier (letters, numbers, and underscores only)."),fe=z.object({handler:$,provider:z.nativeEnum(C).nullish()}),me=z.object({provider:z.nativeEnum(C),event:z.string().min(1),handler:$}),ge=z.object({crons:z.array(pe),events:z.array(me).default([]),webhooks:z.array(fe).default([])});function N(e){let r=Object.create(null);for(let t in e){let o=e[t];r[o]=t;}return r}var _={PARSE_ERROR:-32700,BAD_REQUEST:-32600,INTERNAL_SERVER_ERROR:-32603,NOT_IMPLEMENTED:-32603,UNAUTHORIZED:-32001,FORBIDDEN:-32003,NOT_FOUND:-32004,METHOD_NOT_SUPPORTED:-32005,TIMEOUT:-32008,CONFLICT:-32009,PRECONDITION_FAILED:-32012,PAYLOAD_TOO_LARGE:-32013,UNPROCESSABLE_CONTENT:-32022,TOO_MANY_REQUESTS:-32029,CLIENT_CLOSED_REQUEST:-32099};N(_);N(_);typeof window>"u"||"Deno"in window||globalThis.process?.env?.NODE_ENV==="test"||!!globalThis.process?.env?.JEST_WORKER_ID||!!globalThis.process?.env?.VITEST_WORKER_ID;var P=class e extends Error{static prefix="__MISSING AUTH FOR SCOPE";static jsonRpcCode=-32001;constructor({provider:r,scope:t,accountId:o,popup:n=false}){let s=btoa(JSON.stringify({provider:r,scope:t,accountId:o}));super(`${e.prefix}: ${s}${n?" --popup":" end"}`);}jsonRpcError(){return {code:e.jsonRpcCode,message:this.message}}static check(r){return r?.message?.startsWith(e.prefix)}};function ne({environment:e,dbPath:r="errors.db"}){let t=new Ce(r,{fileMustExist:false});t.pragma("journal_mode = WAL"),t.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS error_logs (
|
|
3
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
|
+
environment TEXT NOT NULL,
|
|
5
|
+
source TEXT NOT NULL,
|
|
6
|
+
message TEXT NOT NULL,
|
|
7
|
+
stack TEXT,
|
|
8
|
+
metadata TEXT,
|
|
9
|
+
request_id TEXT,
|
|
10
|
+
created_at INTEGER NOT NULL DEFAULT (unixepoch())
|
|
11
|
+
)
|
|
12
|
+
`),t.exec(`
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_error_logs_env_created
|
|
14
|
+
ON error_logs (environment, created_at)
|
|
15
|
+
`);let o=t.prepare(`
|
|
16
|
+
INSERT INTO error_logs (environment, source, message, stack, metadata, request_id)
|
|
17
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
18
|
+
`),n=false;function s(c){o.run(e,c.source,c.message,c.stack??null,c.metadata?JSON.stringify(c.metadata):null,c.requestId??null);}function i(c=5){return t.prepare(`
|
|
19
|
+
SELECT COUNT(*) as count FROM error_logs
|
|
20
|
+
WHERE created_at > unixepoch() - ?
|
|
21
|
+
`).get(c*60).count>0}function l(c=50){return t.prepare(`
|
|
22
|
+
SELECT * FROM error_logs
|
|
23
|
+
ORDER BY created_at DESC
|
|
24
|
+
LIMIT ?
|
|
25
|
+
`).all(c)}function a({body:c,requestId:d}){let E=c,m,h;try{let w=JSON.parse(c);E=w.message??c,m=w.stack,h=w.metadata;}catch{}let f=E.startsWith("[console.warn]")||E.startsWith("[console.error]");return f&&s({source:"client",message:E,stack:m,metadata:h,requestId:d}),{message:E,persisted:f}}function u({result:c,requestId:d}){let m=c.json?.error;return m?(s({source:"server",message:m.message??"Unknown RPC error",stack:m.stack,requestId:d,metadata:m.data?{errorData:m.data}:void 0}),true):false}function p({logger:c=console}={}){n||(process.on("uncaughtException",d=>{s({source:"server",message:d.message,stack:d.stack,metadata:{type:"uncaughtException"}}),c.error("Uncaught exception:",d);}),process.on("unhandledRejection",d=>{s({source:"server",message:d instanceof Error?d.message:String(d),stack:d instanceof Error?d.stack:void 0,metadata:{type:"unhandledRejection"}}),c.error("Unhandled rejection:",d);}),n=true);}return {captureClientLog:a,captureRpcError:u,getRecentErrors:l,hasErrors:i,logError:s,registerProcessHandlers:p}}var qe={error:console.error.bind(console),warn:console.warn.bind(console),info:()=>{},debug:()=>{}};function F(e){try{return JSON.parse(e.data)}catch{return null}}function oe({dbPath:e,handlers:r,errorTracker:t,queueName:o="default",logger:n=qe}){let s=new Ce(e,{fileMustExist:false});s.pragma("journal_mode = WAL");let i=better(s),l=defineQueue({connection:i}),a=new Proxy({},{get(m,h){return f=>l.add(o,{action:h,payload:f})}});function u(m){return l.getJobById(m)}function p(){return l.countJobs({status:JobStatus.Processing})}function c(){return l.countJobs({status:JobStatus.Pending})}function d(){return {pending:l.countJobs({status:JobStatus.Pending}),processing:l.countJobs({status:JobStatus.Processing}),done:l.countJobs({status:JobStatus.Done}),failed:l.countJobs({status:JobStatus.Failed})}}function E(){let m=defineWorker(o,async h=>{let f=F(h);if(!f)throw new Error(`Failed to parse queue payload for job ${h.id}`);let w=r[f.action];if(!w)throw new Error(`No handler registered for action: ${f.action}`);console.log(`Processing job ${h.id} with action: ${f.action}`),await w(f.payload,h);},{queue:l,logger:n,onCompleted:h=>{let w=F(h)?.action??"unknown";console.log(`Job ${h.id} completed: ${w}`);},onFailed:(h,f)=>{let w=F(h);t?.logError({source:"worker",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0,metadata:{jobId:h.id,action:w?.action}}),console.error(`Job ${h.id} failed: ${w?.action??"unknown"}`,f);}});return m.start(),m}return {getActiveJobCount:p,getJob:u,getJobCounts:d,getPendingJobCount:c,queue:a,startWorker:E}}var ue=createTRPCProxyClient({transformer:x,links:[]}),y;function kr({baseUrl:e,realtimeDomain:r,guestServicesUrl:t,environment:o,queueDbPath:n,errorsDbPath:s}){return globalThis.env||(globalThis.env={},globalThis.env.BASE_URL=e,globalThis.env.REALTIME_DOMAIN=r,globalThis.env.GUEST_SERVICES_URL=t,ue=createTRPCProxyClient({transformer:x,links:[httpLink({url:t,transformer:x,headers:()=>{let i=Q();if(!i)throw new Error("Missing request context");return {"x-request-id":i.requestId}}})]}),console.log("Adaptive SDK server environment initialized")),y?(y.environment=o,y.queueDbPath=n,y.errorsDbPath=s):y={environment:o,queueDbPath:n,errorsDbPath:s},y}function I(){if(!y)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");return y}function ce(){let e=I();!e.errorTracker&&e.errorsDbPath&&(e.errorTracker=ne({environment:e.environment,dbPath:e.errorsDbPath}),e.errorTracker.registerProcessHandlers());let{errorTracker:r}=e;if(!r)throw new Error("Adaptive SDK error tracking is not initialized. Pass `errorsDbPath` to initializeServerEnvironment first.");return r}function Fe({handlers:e,queueName:r,logger:t,autoStartWorker:o=true}){let n=I();if(!n.queue){if(!n.queueDbPath)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");n.queue=oe({dbPath:n.queueDbPath,handlers:e,queueName:r,logger:t,errorTracker:n.errorsDbPath?ce():void 0});}o&&!n.queueWorkerStarted&&(n.queue.startWorker(),n.queueWorkerStarted=true);let{queue:s}=n;if(!s)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return s}function Nr(){return new Proxy({},{get(e,r){let t=I();if(!t.queue)throw new Error("Adaptive SDK queue is not initialized. Pass `queueDbPath` to initializeServerEnvironment first.");return r==="getJob"?t.queue.getJob:t.queue.queue[r]}})}function j(e,r){return r.endsWith("*")?e.startsWith(r.slice(0,-1)):e===r}function Dr({procedures:e,jobs:r,transcoder:t,rpcPath:o="/api/*",loggerPath:n="/_logger",queueStatusPath:s="/_queue/status"}){let i=I(),l=i.errorsDbPath?ce():void 0,a=r&&i.queueDbPath?Fe({handlers:r}):void 0;return async(u,p)=>{let c=new URL(u.req.url).pathname;if(n&&l&&u.req.method==="POST"&&j(c,n)){let d=await u.req.text(),E=u.req.header("x-request-id"),{message:m}=l.captureClientLog({body:d,requestId:E??void 0});return console.log("[browser]",m),u.json({status:"ok"})}if(s&&a&&u.req.method==="GET"&&j(c,s))return u.json({activeJobs:a.getActiveJobCount(),pendingJobs:a.getPendingJobCount()});if(u.req.method==="POST"&&j(c,o)){let d=await u.req.json(),E=u.req.header("x-request-id"),m=u.req.header("x-channel-id");E||console.warn("Request is missing x-request-id header. Adaptive AI SDK relies on this for request context."),console.log(`[${E}] Starting request ${u.req.method} ${u.req.url}`),m&&console.log(`[${E}] Channel ID: ${m}`);let f=await Qe({requestId:E??"unknown-request-id",channelId:m,hasTasks:false},async()=>await handleRpc(d,e,{transcoder:t}));return console.log(`[${E}] Response:`,inspect(f,{depth:3,colors:true})),l?.captureRpcError({result:f,requestId:E??void 0}),u.json(f)}await p();}}var de=new AsyncLocalStorage,je=new Proxy({},{get(e,r){return async t=>{if(globalThis.env===void 0)throw new Error("Adaptive SDK server environment is not initialized. Please call initializeServerEnvironment first.");let n=ue[r];if(!n||typeof n.mutate!="function")throw new Error(`Property "${String(r)}" is not a mutation procedure`);return n.mutate(t)}}});function Q(){return de.getStore()}function qr(e){let r=Q();r&&Object.assign(r,e);}async function Qe(e,r){return de.run(e,r)}function Hr(){return globalThis.env.BASE_URL}var J=null;function Lr(){return J}function Mr({channelId:e,onUpdate:r}){let t=new WebSocket(`wss://${globalThis.env.REALTIME_DOMAIN}/${e}`),o=-1;function n(s){r&&(J=Date.now());try{let i=JSON.parse(s.data.toString());if(i?.id&&i.id>o){let l=x.parse(i.payload);r?.(l),o=i.id;}}catch{}}return t.addEventListener("message",n),{destroy(){t.close(),t.removeEventListener("message",n);}}}async function se({channelId:e,data:r}){J=Date.now(),await fetch(`https://${globalThis.env.REALTIME_DOMAIN}/${e}`,{method:"POST",body:x.stringify(r)}).catch(console.error);}async function Ur(){let e,r=Q()?.channelId;if(!r)throw new Error("API's using `startRealtimeResponse` must be called via `useRealtimeMutation`.");return {next(t){e=t,se({channelId:r,data:t});},end(){return se({channelId:r,data:e}),e}}}function ie(e){throw new P({provider:"AC1",popup:true})}async function Fr(e){let r=await je.getCurrentUser();if(r?.error==="SEED")throw new Error('Call to "getAuth" in seed function is not allowed. Seed functions should not depend on user data.');if(r.userId)return {userId:r.userId,status:"authenticated",signIn:ie,providers:r.providers};if(e?.required)throw new P({provider:"AC1"});return {userId:null,status:"unauthenticated",signIn:ie,providers:[]}}
|
|
26
|
+
export{ge as appConfigSchema,Fr as getAuth,Hr as getBaseUrl,ce as getErrorTracker,Lr as getLastStreamTime,Nr as getQueue,Mr as getRealtimeStore,Q as getRequestContext,Dr as honoMiddleware,kr as initializeServerEnvironment,je as mcp,Qe as runWithContext,se as setRealtimeStore,qr as setRequestContext,Ur as startRealtimeResponse};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adaptive-ai/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.30",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"README.md",
|
|
19
19
|
"LICENSE"
|
|
20
20
|
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"better-sqlite3": "^12.5.0",
|
|
23
|
+
"plainjob": "^0.0.14"
|
|
24
|
+
},
|
|
21
25
|
"scripts": {
|
|
22
26
|
"build:dev": "pnpm run build && ./distribute-local.sh",
|
|
23
27
|
"lint": "NODE_OPTIONS='--max-old-space-size=8192' eslint --cache .",
|
|
@@ -58,6 +62,7 @@
|
|
|
58
62
|
"@ac1/core": "workspace:*",
|
|
59
63
|
"@ac1/iso": "workspace:*",
|
|
60
64
|
"@types/eslint": "^8.44.2",
|
|
65
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
61
66
|
"@types/lodash": "^4.14.200",
|
|
62
67
|
"@types/node": "^20.14.8",
|
|
63
68
|
"@types/object-inspect": "^1.13.0",
|