@terreno/test 57.17.0 → 57.19.2
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/CHANGELOG.md +1681 -0
- package/README.md +6 -0
- package/dist/assertions/expectAPIError.d.ts +18 -0
- package/dist/assertions/expectAPIError.js +33 -0
- package/dist/assertions/strictResponseProperties.d.ts +14 -0
- package/dist/assertions/strictResponseProperties.js +37 -0
- package/dist/cache/mongoTestCache.js +2 -2
- package/dist/cli/collectFiles.d.ts +38 -0
- package/dist/cli/collectFiles.js +73 -0
- package/dist/cli/testHygiene.d.ts +134 -0
- package/dist/cli/testHygiene.js +357 -0
- package/dist/cli/testHygieneCli.d.ts +2 -0
- package/dist/cli/testHygieneCli.js +5 -0
- package/dist/cli/testHygieneRules.d.ts +58 -0
- package/dist/cli/testHygieneRules.js +517 -0
- package/dist/cli/testShard.d.ts +155 -0
- package/dist/cli/testShard.js +377 -0
- package/dist/cli/testShardCli.d.ts +2 -0
- package/dist/cli/testShardCli.js +5 -0
- package/dist/expo/authTokenStorage.d.ts +76 -0
- package/dist/expo/authTokenStorage.js +160 -0
- package/dist/expo/expoModuleMocks.d.ts +24 -0
- package/dist/expo/expoModuleMocks.js +456 -0
- package/dist/expo/libraryModuleMocks.d.ts +17 -0
- package/dist/expo/libraryModuleMocks.js +347 -0
- package/dist/expo/mockHelpers.d.ts +39 -0
- package/dist/expo/mockHelpers.js +45 -0
- package/dist/expo/mockModuleAliases.d.ts +50 -0
- package/dist/expo/mockModuleAliases.js +174 -0
- package/dist/expo/reactNativeMock.d.ts +39 -0
- package/dist/expo/reactNativeMock.js +421 -0
- package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
- package/dist/expo/registerExpoTestEnvironment.js +163 -0
- package/dist/expo/renderWithTerreno.d.ts +47 -0
- package/dist/expo/renderWithTerreno.js +47 -0
- package/dist/http/authWithToken.d.ts +20 -0
- package/dist/http/authWithToken.js +30 -0
- package/dist/index.d.ts +14 -1
- package/dist/index.js +33 -1
- package/dist/logging/silenceLogs.js +0 -2
- package/dist/mocks/aiSdk.d.ts +77 -0
- package/dist/mocks/aiSdk.js +102 -0
- package/dist/mocks/cloudTasks.d.ts +91 -0
- package/dist/mocks/cloudTasks.js +197 -0
- package/dist/mocks/expoPush.d.ts +53 -0
- package/dist/mocks/expoPush.js +57 -0
- package/dist/mocks/gcs.d.ts +101 -0
- package/dist/mocks/gcs.js +162 -0
- package/dist/mocks/googleAuth.d.ts +69 -0
- package/dist/mocks/googleAuth.js +55 -0
- package/dist/mocks/mockGroup.d.ts +11 -0
- package/dist/mocks/mockGroup.js +21 -0
- package/dist/mocks/notifiers.d.ts +21 -0
- package/dist/mocks/notifiers.js +26 -0
- package/dist/mocks/sendgrid.d.ts +22 -0
- package/dist/mocks/sendgrid.js +32 -0
- package/dist/mocks/twilio.d.ts +72 -0
- package/dist/mocks/twilio.js +64 -0
- package/dist/preload/registerBackendPreload.js +4 -1
- package/dist/time/freezeTime.d.ts +16 -0
- package/dist/time/freezeTime.js +49 -0
- package/dist/transaction/testTransaction.d.ts +43 -6
- package/dist/transaction/testTransaction.js +371 -92
- package/dist/utils/waitUntil.d.ts +22 -0
- package/dist/utils/waitUntil.js +34 -0
- package/package.json +53 -8
- package/src/assertions/expectAPIError.ts +51 -0
- package/src/assertions/strictResponseProperties.ts +42 -0
- package/src/cache/mongoTestCache.ts +2 -2
- package/src/cli/collectFiles.ts +115 -0
- package/src/cli/testHygiene.ts +539 -0
- package/src/cli/testHygieneCli.ts +4 -0
- package/src/cli/testHygieneRules.ts +719 -0
- package/src/cli/testShard.ts +532 -0
- package/src/cli/testShardCli.ts +4 -0
- package/src/expo/authTokenStorage.ts +198 -0
- package/src/expo/expoModuleMocks.ts +503 -0
- package/src/expo/libraryModuleMocks.ts +411 -0
- package/src/expo/mockHelpers.ts +73 -0
- package/src/expo/mockModuleAliases.ts +252 -0
- package/src/expo/reactNativeMock.ts +534 -0
- package/src/expo/registerExpoTestEnvironment.ts +260 -0
- package/src/expo/renderWithTerreno.ts +79 -0
- package/src/http/authWithToken.ts +38 -0
- package/src/index.ts +82 -1
- package/src/logging/silenceLogs.ts +0 -2
- package/src/mocks/aiSdk.ts +199 -0
- package/src/mocks/cloudTasks.ts +323 -0
- package/src/mocks/expoPush.ts +134 -0
- package/src/mocks/gcs.ts +305 -0
- package/src/mocks/googleAuth.ts +136 -0
- package/src/mocks/mockGroup.ts +32 -0
- package/src/mocks/notifiers.ts +36 -0
- package/src/mocks/sendgrid.ts +57 -0
- package/src/mocks/twilio.ts +143 -0
- package/src/preload/registerBackendPreload.ts +4 -1
- package/src/time/freezeTime.ts +61 -0
- package/src/transaction/testTransaction.ts +456 -124
- package/src/utils/waitUntil.ts +47 -0
- package/biome.jsonc +0 -20
- package/bunfig.toml +0 -16
- package/src/cache/mongoTestCache.test.ts +0 -103
- package/src/env/setTerrenoTestEnv.test.ts +0 -26
- package/src/http/authAsUser.test.ts +0 -40
- package/src/http/getBaseServer.test.ts +0 -45
- package/src/logging/setupEnvironment.test.ts +0 -24
- package/src/logging/silenceLogs.test.ts +0 -52
- package/src/logging/testLogger.test.ts +0 -58
- package/src/mocks/sentryBun.test.ts +0 -230
- package/src/mongo/connection.test.ts +0 -43
- package/src/mongo/mongoServer.test.ts +0 -99
- package/src/preload/registerBackendPreload.test.ts +0 -10
- package/src/transaction/testTransaction.test.ts +0 -64
- package/src/utils/helpers.test.ts +0 -46
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerExpoTestEnvironment = exports.createDefaultExpoModuleMocks = exports.ASSET_FILE_PATTERN = void 0;
|
|
4
|
+
const bun_test_1 = require("bun:test");
|
|
5
|
+
const luxon_1 = require("luxon");
|
|
6
|
+
const authTokenStorage_1 = require("./authTokenStorage");
|
|
7
|
+
const expoModuleMocks_1 = require("./expoModuleMocks");
|
|
8
|
+
const libraryModuleMocks_1 = require("./libraryModuleMocks");
|
|
9
|
+
const reactNativeMock_1 = require("./reactNativeMock");
|
|
10
|
+
/** File extensions served as `{uri, width, height}` stubs instead of being parsed as code. */
|
|
11
|
+
exports.ASSET_FILE_PATTERN = /\.(png|jpe?g|gif|webp|bmp|svg|ttf|otf|woff2?|mp3|mp4|wav|m4a|mov)$/u;
|
|
12
|
+
let isAssetPluginInstalled = false;
|
|
13
|
+
const installAssetPlugin = () => {
|
|
14
|
+
if (isAssetPluginInstalled) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
isAssetPluginInstalled = true;
|
|
18
|
+
// Metro turns asset imports into descriptors; Bun would try to parse the bytes as JavaScript.
|
|
19
|
+
Bun.plugin({
|
|
20
|
+
name: "terreno-expo-asset-stub",
|
|
21
|
+
setup(build) {
|
|
22
|
+
build.onLoad({ filter: exports.ASSET_FILE_PATTERN }, () => ({
|
|
23
|
+
exports: { default: { height: 1, uri: "test-asset", width: 1 } },
|
|
24
|
+
loader: "object",
|
|
25
|
+
}));
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
const installGlobals = () => {
|
|
30
|
+
const globals = globalThis;
|
|
31
|
+
globals.__DEV__ = true;
|
|
32
|
+
globals.IS_REACT_ACT_ENVIRONMENT = true;
|
|
33
|
+
if (globals.expo !== undefined) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
// expo-modules-core reads `globalThis.expo` when it loads, before any native module call.
|
|
37
|
+
globals.expo = (0, expoModuleMocks_1.createExpoGlobal)();
|
|
38
|
+
};
|
|
39
|
+
const tryResolve = (specifier, fromDirectory) => {
|
|
40
|
+
try {
|
|
41
|
+
return Bun.resolveSync(specifier, fromDirectory);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** Every module the environment mocks by default, keyed by specifier. */
|
|
48
|
+
const createDefaultExpoModuleMocks = ({ nestedPackagePrefixes = [], platform = "ios", ...expoOptions } = {}) => ({
|
|
49
|
+
...(0, reactNativeMock_1.createReactNativeModuleMocks)({ packagePrefixes: ["", ...nestedPackagePrefixes], platform }),
|
|
50
|
+
...(0, expoModuleMocks_1.createExpoModuleMocks)({ ...expoOptions, platform }),
|
|
51
|
+
...(0, libraryModuleMocks_1.createLibraryModuleMocks)(),
|
|
52
|
+
...(0, authTokenStorage_1.createAuthTokenStorageModuleMocks)(),
|
|
53
|
+
});
|
|
54
|
+
exports.createDefaultExpoModuleMocks = createDefaultExpoModuleMocks;
|
|
55
|
+
const resolveCleanup = (cleanup) => {
|
|
56
|
+
if (cleanup === false) {
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
const options = cleanup === true || cleanup === undefined ? {} : cleanup;
|
|
60
|
+
return {
|
|
61
|
+
clearStorage: options.clearStorage ?? true,
|
|
62
|
+
resetDevFlag: options.resetDevFlag ?? true,
|
|
63
|
+
restoreMocks: options.restoreMocks ?? true,
|
|
64
|
+
restoreModules: options.restoreModules ?? [],
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Prepares Bun to run Expo / React Native component tests. Call it from a `bunfig.toml` preload
|
|
69
|
+
* (or at the top of a test file, then `await import()` what the test renders) before anything
|
|
70
|
+
* imports `react-native`:
|
|
71
|
+
*
|
|
72
|
+
* - mocks `react-native` and its Flow-only internals, the common `expo-*` modules,
|
|
73
|
+
* `expo-router`, `@expo/vector-icons`, and common native libraries (Reanimated, Gesture
|
|
74
|
+
* Handler, SVG, safe-area-context, NetInfo, SecureStore, AsyncStorage, ...);
|
|
75
|
+
* - sets `__DEV__`, `IS_REACT_ACT_ENVIRONMENT`, `globalThis.expo`, `TZ`, and `EXPO_OS`;
|
|
76
|
+
* - stubs image / font / media imports;
|
|
77
|
+
* - installs an `afterEach` that restores spies, empties the in-memory storage, and resets
|
|
78
|
+
* `__DEV__`.
|
|
79
|
+
*
|
|
80
|
+
* `skip` leaves a module real; `overrides` replaces or adds a factory.
|
|
81
|
+
*/
|
|
82
|
+
const registerExpoTestEnvironment = (options = {}) => {
|
|
83
|
+
const { cleanup, fixedNow, overrides = {}, platform = "ios", resolveFrom = process.cwd(), setProcessEnv = true, skip = [], stubAssets = true, timeZone = "America/New_York", } = options;
|
|
84
|
+
const frozenAt = fixedNow ? luxon_1.DateTime.fromISO(fixedNow, { setZone: true }) : undefined;
|
|
85
|
+
if (frozenAt && !frozenAt.isValid) {
|
|
86
|
+
throw new Error(`registerExpoTestEnvironment: fixedNow "${fixedNow}" is not an ISO timestamp`);
|
|
87
|
+
}
|
|
88
|
+
if (setProcessEnv) {
|
|
89
|
+
process.env.TZ = timeZone;
|
|
90
|
+
process.env.EXPO_OS = platform;
|
|
91
|
+
}
|
|
92
|
+
installGlobals();
|
|
93
|
+
if (stubAssets) {
|
|
94
|
+
installAssetPlugin();
|
|
95
|
+
}
|
|
96
|
+
const skipped = new Set(skip);
|
|
97
|
+
const defaults = (0, exports.createDefaultExpoModuleMocks)({
|
|
98
|
+
expoConfig: options.expoConfig,
|
|
99
|
+
locale: options.locale,
|
|
100
|
+
nestedPackagePrefixes: options.nestedPackagePrefixes,
|
|
101
|
+
platform,
|
|
102
|
+
scheme: options.scheme,
|
|
103
|
+
timeZone,
|
|
104
|
+
});
|
|
105
|
+
const factories = { ...defaults, ...overrides };
|
|
106
|
+
const register = (specifier, factory) => {
|
|
107
|
+
bun_test_1.mock.module(specifier, factory);
|
|
108
|
+
if (resolveFrom === false) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const appPath = tryResolve(specifier, resolveFrom);
|
|
112
|
+
if (appPath && appPath !== tryResolve(specifier, __dirname)) {
|
|
113
|
+
bun_test_1.mock.module(appPath, factory);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const mockedModules = [];
|
|
117
|
+
for (const [specifier, factory] of Object.entries(factories)) {
|
|
118
|
+
if (skipped.has(specifier)) {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
register(specifier, factory);
|
|
122
|
+
mockedModules.push(specifier);
|
|
123
|
+
}
|
|
124
|
+
const restoreModuleMock = (specifier) => {
|
|
125
|
+
const factory = factories[specifier];
|
|
126
|
+
if (!factory || skipped.has(specifier)) {
|
|
127
|
+
throw new Error(`registerExpoTestEnvironment does not mock "${specifier}"`);
|
|
128
|
+
}
|
|
129
|
+
register(specifier, factory);
|
|
130
|
+
};
|
|
131
|
+
if (frozenAt) {
|
|
132
|
+
(0, bun_test_1.beforeEach)(() => {
|
|
133
|
+
(0, bun_test_1.setSystemTime)(frozenAt.toJSDate());
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
const cleanupSteps = resolveCleanup(cleanup);
|
|
137
|
+
const isStorageMocked = !skipped.has("expo-secure-store") && !("expo-secure-store" in overrides);
|
|
138
|
+
if (cleanupSteps || frozenAt) {
|
|
139
|
+
(0, bun_test_1.afterEach)(() => {
|
|
140
|
+
if (frozenAt) {
|
|
141
|
+
(0, bun_test_1.setSystemTime)();
|
|
142
|
+
}
|
|
143
|
+
if (!cleanupSteps) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (cleanupSteps.restoreMocks) {
|
|
147
|
+
bun_test_1.mock.restore();
|
|
148
|
+
}
|
|
149
|
+
if (cleanupSteps.clearStorage && isStorageMocked) {
|
|
150
|
+
(0, authTokenStorage_1.clearAuthTokenStorage)();
|
|
151
|
+
(0, authTokenStorage_1.resetAuthTokenStorageMocks)();
|
|
152
|
+
}
|
|
153
|
+
if (cleanupSteps.resetDevFlag) {
|
|
154
|
+
globalThis.__DEV__ = true;
|
|
155
|
+
}
|
|
156
|
+
for (const specifier of cleanupSteps.restoreModules) {
|
|
157
|
+
restoreModuleMock(specifier);
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return { mockedModules, restoreModuleMock };
|
|
162
|
+
};
|
|
163
|
+
exports.registerExpoTestEnvironment = registerExpoTestEnvironment;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type TerrenoProviderProps } from "@terreno/ui";
|
|
2
|
+
import { type RenderOptions, type RenderResult } from "@testing-library/react-native";
|
|
3
|
+
import { type ComponentType, type ReactElement, type ReactNode } from "react";
|
|
4
|
+
/** The slice of a Redux store `react-redux`'s `Provider` needs. */
|
|
5
|
+
export interface ReduxStoreLike {
|
|
6
|
+
dispatch: (action: never) => unknown;
|
|
7
|
+
getState: () => unknown;
|
|
8
|
+
subscribe: (listener: () => void) => () => void;
|
|
9
|
+
}
|
|
10
|
+
/** `TerrenoProvider` props a test can set: color scheme, theme primitives, icons, OpenAPI URL. */
|
|
11
|
+
export type TerrenoThemeOptions = Omit<TerrenoProviderProps, "children">;
|
|
12
|
+
/** Options for `renderWithTerreno` and `createTerrenoWrapper`. */
|
|
13
|
+
export interface RenderWithTerrenoOptions extends Omit<RenderOptions, "wrapper"> {
|
|
14
|
+
/** Redux store to provide. Requires the optional `react-redux` peer dependency. */
|
|
15
|
+
store?: ReduxStoreLike;
|
|
16
|
+
/** Props passed to `TerrenoProvider`. */
|
|
17
|
+
theme?: TerrenoThemeOptions;
|
|
18
|
+
/** Extra provider rendered inside `TerrenoProvider`, around the element under test. */
|
|
19
|
+
wrapper?: ComponentType<{
|
|
20
|
+
children: ReactNode;
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
type ProviderComponent = ComponentType<{
|
|
24
|
+
children?: ReactNode;
|
|
25
|
+
store: ReduxStoreLike;
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* `react-redux` is optional, so it is only loaded when a test passes a store. `load` exists so the
|
|
29
|
+
* missing-package error can be tested without uninstalling the package.
|
|
30
|
+
*/
|
|
31
|
+
export declare const loadReduxProvider: (load?: () => unknown) => ProviderComponent;
|
|
32
|
+
/**
|
|
33
|
+
* Builds the wrapper `renderWithTerreno` uses — an optional Redux `Provider`, then
|
|
34
|
+
* `TerrenoProvider`, then `wrapper` — for `renderHook` or a custom `render` call.
|
|
35
|
+
*/
|
|
36
|
+
export declare const createTerrenoWrapper: ({ store, theme, wrapper: InnerWrapper, }?: Pick<RenderWithTerrenoOptions, "store" | "theme" | "wrapper">) => ComponentType<{
|
|
37
|
+
children: ReactNode;
|
|
38
|
+
}>;
|
|
39
|
+
/**
|
|
40
|
+
* Renders `ui` with `@testing-library/react-native` inside `TerrenoProvider` (theme, icons,
|
|
41
|
+
* toasts, portal host), and inside a Redux `Provider` when `store` is given.
|
|
42
|
+
*
|
|
43
|
+
* Requires the optional peers `@terreno/ui`, `@testing-library/react-native`, `react`, and
|
|
44
|
+
* `react-native` (mocked by `registerExpoTestEnvironment`), plus `react-redux` for `store`.
|
|
45
|
+
*/
|
|
46
|
+
export declare const renderWithTerreno: (ui: ReactElement, { store, theme, wrapper, ...renderOptions }?: RenderWithTerrenoOptions) => RenderResult;
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderWithTerreno = exports.createTerrenoWrapper = exports.loadReduxProvider = void 0;
|
|
4
|
+
const ui_1 = require("@terreno/ui");
|
|
5
|
+
const react_native_1 = require("@testing-library/react-native");
|
|
6
|
+
const react_1 = require("react");
|
|
7
|
+
/**
|
|
8
|
+
* `react-redux` is optional, so it is only loaded when a test passes a store. `load` exists so the
|
|
9
|
+
* missing-package error can be tested without uninstalling the package.
|
|
10
|
+
*/
|
|
11
|
+
const loadReduxProvider = (load = () => require("react-redux")) => {
|
|
12
|
+
try {
|
|
13
|
+
return load().Provider;
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
throw new Error("renderWithTerreno: passing `store` requires the `react-redux` package. Install it as a devDependency.", { cause: error });
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
exports.loadReduxProvider = loadReduxProvider;
|
|
20
|
+
/**
|
|
21
|
+
* Builds the wrapper `renderWithTerreno` uses — an optional Redux `Provider`, then
|
|
22
|
+
* `TerrenoProvider`, then `wrapper` — for `renderHook` or a custom `render` call.
|
|
23
|
+
*/
|
|
24
|
+
const createTerrenoWrapper = ({ store, theme = {}, wrapper: InnerWrapper, } = {}) => {
|
|
25
|
+
const ReduxProvider = store ? (0, exports.loadReduxProvider)() : undefined;
|
|
26
|
+
const TerrenoWrapper = ({ children }) => {
|
|
27
|
+
const content = InnerWrapper ? (0, react_1.createElement)(InnerWrapper, null, children) : children;
|
|
28
|
+
const themed = (0, react_1.createElement)(ui_1.TerrenoProvider, { ...theme, children: content });
|
|
29
|
+
if (!ReduxProvider || !store) {
|
|
30
|
+
return themed;
|
|
31
|
+
}
|
|
32
|
+
return (0, react_1.createElement)(ReduxProvider, { store }, themed);
|
|
33
|
+
};
|
|
34
|
+
return TerrenoWrapper;
|
|
35
|
+
};
|
|
36
|
+
exports.createTerrenoWrapper = createTerrenoWrapper;
|
|
37
|
+
/**
|
|
38
|
+
* Renders `ui` with `@testing-library/react-native` inside `TerrenoProvider` (theme, icons,
|
|
39
|
+
* toasts, portal host), and inside a Redux `Provider` when `store` is given.
|
|
40
|
+
*
|
|
41
|
+
* Requires the optional peers `@terreno/ui`, `@testing-library/react-native`, `react`, and
|
|
42
|
+
* `react-native` (mocked by `registerExpoTestEnvironment`), plus `react-redux` for `store`.
|
|
43
|
+
*/
|
|
44
|
+
const renderWithTerreno = (ui, { store, theme, wrapper, ...renderOptions } = {}) => {
|
|
45
|
+
return (0, react_native_1.render)(ui, { ...renderOptions, wrapper: (0, exports.createTerrenoWrapper)({ store, theme, wrapper }) });
|
|
46
|
+
};
|
|
47
|
+
exports.renderWithTerreno = renderWithTerreno;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import type TestAgent from "supertest/lib/agent";
|
|
3
|
+
export interface AuthWithTokenOptions {
|
|
4
|
+
/** Access token to send, usually minted with `@terreno/api`'s `generateTokens(user, authOptions)`. */
|
|
5
|
+
token: string | null | undefined;
|
|
6
|
+
/** Extra headers set on every request, e.g. `{"app-version": "1.10.0"}`. */
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Returns a supertest agent that sends `Authorization: Bearer <token>` on every request.
|
|
11
|
+
*
|
|
12
|
+
* Pair it with a token minted directly from the user to skip `POST /auth/login`, whose password
|
|
13
|
+
* hashing costs ~200ms per call. Keep `authAsUser` for tests that exercise the login flow itself.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* const {token} = await generateTokens(user, authOptions);
|
|
17
|
+
* const agent = await authWithToken(app, {token});
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare const authWithToken: (app: express.Application, { token, headers }: AuthWithTokenOptions) => Promise<TestAgent>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.authWithToken = void 0;
|
|
7
|
+
const supertest_1 = __importDefault(require("supertest"));
|
|
8
|
+
/**
|
|
9
|
+
* Returns a supertest agent that sends `Authorization: Bearer <token>` on every request.
|
|
10
|
+
*
|
|
11
|
+
* Pair it with a token minted directly from the user to skip `POST /auth/login`, whose password
|
|
12
|
+
* hashing costs ~200ms per call. Keep `authAsUser` for tests that exercise the login flow itself.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* const {token} = await generateTokens(user, authOptions);
|
|
16
|
+
* const agent = await authWithToken(app, {token});
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
const authWithToken = async (app, { token, headers = {} }) => {
|
|
20
|
+
if (!token) {
|
|
21
|
+
throw new Error("authWithToken: token is empty; check that the user exists and TOKEN_SECRET is set");
|
|
22
|
+
}
|
|
23
|
+
const agent = supertest_1.default.agent(app);
|
|
24
|
+
await agent.set("authorization", `Bearer ${token}`);
|
|
25
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
26
|
+
await agent.set(key, value);
|
|
27
|
+
}
|
|
28
|
+
return agent;
|
|
29
|
+
};
|
|
30
|
+
exports.authWithToken = authWithToken;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,27 @@
|
|
|
1
|
+
export { type ExpectedAPIError, expectAPIError } from "./assertions/expectAPIError";
|
|
2
|
+
export { assertStrictResponseProperties, collectPropertyPaths, } from "./assertions/strictResponseProperties";
|
|
1
3
|
export { createMongoTestCache, type MongoTestCacheController, type MongoTestCacheOptions, } from "./cache/mongoTestCache";
|
|
2
4
|
export { setTerrenoTestEnv, type TerrenoTestEnvOptions } from "./env/setTerrenoTestEnv";
|
|
3
5
|
export { type AuthAsUserOptions, type AuthUserCredentials, authAsUser } from "./http/authAsUser";
|
|
6
|
+
export { type AuthWithTokenOptions, authWithToken } from "./http/authWithToken";
|
|
4
7
|
export { type GetBaseServerOptions, getBaseServer } from "./http/getBaseServer";
|
|
5
8
|
export { createLogSilencer, registerLogSilencing, type SilenceLogsController, type SilenceLogsOptions, } from "./logging/silenceLogs";
|
|
9
|
+
export { type CreateMockLanguageModelOptions, createMockLanguageModel, type MockLanguageModel, type MockLanguageModelFinishReason, type MockLanguageModelGenerateResult, type MockLanguageModelResponse, type MockLanguageModelStreamPart, type MockLanguageModelToolCall, type MockLanguageModelUsage, mockLanguageModelStreamParts, } from "./mocks/aiSdk";
|
|
10
|
+
export { type CloudTasksCreateTaskRequest, type CloudTasksHttpRequest, type CloudTasksMock, type CloudTasksMockClient, type CloudTasksTask, type CloudTasksTime, type DrainCloudTasksOptions, type DrainedCloudTask, decodeCloudTaskBody, type EnqueuedCloudTask, registerCloudTasksMock, } from "./mocks/cloudTasks";
|
|
11
|
+
export { type ExpoMockClient, type ExpoMockPushMessage, type ExpoMockPushReceipt, type ExpoMockPushTicket, type ExpoPushMock, registerExpoPushMock, } from "./mocks/expoPush";
|
|
12
|
+
export { type GcsFileMocks, type GcsGetFilesQuery, type GcsMock, type GcsMockBucket, type GcsMockFile, type GcsObjectMetadata, type GcsSaveOptions, type GcsStoredObject, registerGcsMock, } from "./mocks/gcs";
|
|
13
|
+
export { type GoogleAuthMock, type GoogleAuthMockClient, type GoogleAuthMockIdTokenPayload, type GoogleAuthMockRequestOptions, type GoogleAuthMockResponse, type GoogleAuthMockTicket, type RegisterGoogleAuthMockOptions, registerGoogleAuthMock, } from "./mocks/googleAuth";
|
|
14
|
+
export { registerTerrenoNotifierMocks, type TerrenoNotifierMocks } from "./mocks/notifiers";
|
|
15
|
+
export { registerSendGridMock, type SendGridMock, type SendGridMockResponse, type SendGridMockSendResult, } from "./mocks/sendgrid";
|
|
6
16
|
export { registerSentryBunMock } from "./mocks/sentryBun";
|
|
17
|
+
export { registerTwilioMock, type TwilioMessageCreateParams, type TwilioMock, type TwilioMockClient, type TwilioMockMessage, type TwilioMockVerification, type TwilioMockVerificationCheck, type TwilioMockVerifyService, } from "./mocks/twilio";
|
|
7
18
|
export { buildDatabaseUri, DEFAULT_LOCAL_MONGO_URI, type EnsureTestMongooseConnectedOptions, ensureTestMongooseConnected, type SplitMongoUriResult, splitMongoUri, } from "./mongo/connection";
|
|
8
19
|
export { ensureMongoBinary } from "./mongo/ensureMongoBinary";
|
|
9
20
|
export { getMongoServerUri, initializeModels, type MemoryMongoHandle, type MongoServerOptions, resolveMongoLaunchTimeoutMs, restartMongoServer, startMongoServer, stopMongoServer, waitForDatabaseReady, } from "./mongo/mongoServer";
|
|
10
21
|
export { type BackendPreloadOptions, registerBackendPreload, registerSimpleMongoPreload, type SimpleMongoPreloadOptions, } from "./preload/registerBackendPreload";
|
|
11
|
-
export {
|
|
22
|
+
export { type FreezeTimeInput, type FreezeTimeOptions, freezeTime } from "./time/freezeTime";
|
|
23
|
+
export { type AbortTestTransactionOptions, abortTestTransaction, getTestSession, installTransactionPatches, isTestTransactionOperationCancelled, resetTestSessionAfterReconnect, startTestTransaction, TestTransactionOperationCancelledError, } from "./transaction/testTransaction";
|
|
12
24
|
export { ensureAllIndexes } from "./utils/ensureAllIndexes";
|
|
13
25
|
export { timeout } from "./utils/timeout";
|
|
14
26
|
export { type WaitForDocumentsOptions, waitForDocument, waitForDocuments, } from "./utils/waitForDocuments";
|
|
27
|
+
export { type WaitUntilOptions, waitForCalls, waitUntil } from "./utils/waitUntil";
|
package/dist/index.js
CHANGED
|
@@ -1,19 +1,44 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.waitForDocuments = exports.waitForDocument = exports.timeout = exports.ensureAllIndexes = exports.startTestTransaction = exports.resetTestSessionAfterReconnect = exports.installTransactionPatches = exports.getTestSession = exports.abortTestTransaction = exports.registerSimpleMongoPreload = exports.registerBackendPreload = exports.waitForDatabaseReady = exports.stopMongoServer = exports.startMongoServer = exports.restartMongoServer = exports.resolveMongoLaunchTimeoutMs = exports.initializeModels = exports.getMongoServerUri = exports.ensureMongoBinary = exports.splitMongoUri = exports.ensureTestMongooseConnected = exports.DEFAULT_LOCAL_MONGO_URI = exports.buildDatabaseUri = exports.registerSentryBunMock = exports.registerLogSilencing = exports.createLogSilencer = exports.getBaseServer = exports.authAsUser = exports.setTerrenoTestEnv = exports.createMongoTestCache = void 0;
|
|
3
|
+
exports.waitUntil = exports.waitForCalls = exports.waitForDocuments = exports.waitForDocument = exports.timeout = exports.ensureAllIndexes = exports.TestTransactionOperationCancelledError = exports.startTestTransaction = exports.resetTestSessionAfterReconnect = exports.isTestTransactionOperationCancelled = exports.installTransactionPatches = exports.getTestSession = exports.abortTestTransaction = exports.freezeTime = exports.registerSimpleMongoPreload = exports.registerBackendPreload = exports.waitForDatabaseReady = exports.stopMongoServer = exports.startMongoServer = exports.restartMongoServer = exports.resolveMongoLaunchTimeoutMs = exports.initializeModels = exports.getMongoServerUri = exports.ensureMongoBinary = exports.splitMongoUri = exports.ensureTestMongooseConnected = exports.DEFAULT_LOCAL_MONGO_URI = exports.buildDatabaseUri = exports.registerTwilioMock = exports.registerSentryBunMock = exports.registerSendGridMock = exports.registerTerrenoNotifierMocks = exports.registerGoogleAuthMock = exports.registerGcsMock = exports.registerExpoPushMock = exports.registerCloudTasksMock = exports.decodeCloudTaskBody = exports.mockLanguageModelStreamParts = exports.createMockLanguageModel = exports.registerLogSilencing = exports.createLogSilencer = exports.getBaseServer = exports.authWithToken = exports.authAsUser = exports.setTerrenoTestEnv = exports.createMongoTestCache = exports.collectPropertyPaths = exports.assertStrictResponseProperties = exports.expectAPIError = void 0;
|
|
4
|
+
var expectAPIError_1 = require("./assertions/expectAPIError");
|
|
5
|
+
Object.defineProperty(exports, "expectAPIError", { enumerable: true, get: function () { return expectAPIError_1.expectAPIError; } });
|
|
6
|
+
var strictResponseProperties_1 = require("./assertions/strictResponseProperties");
|
|
7
|
+
Object.defineProperty(exports, "assertStrictResponseProperties", { enumerable: true, get: function () { return strictResponseProperties_1.assertStrictResponseProperties; } });
|
|
8
|
+
Object.defineProperty(exports, "collectPropertyPaths", { enumerable: true, get: function () { return strictResponseProperties_1.collectPropertyPaths; } });
|
|
4
9
|
var mongoTestCache_1 = require("./cache/mongoTestCache");
|
|
5
10
|
Object.defineProperty(exports, "createMongoTestCache", { enumerable: true, get: function () { return mongoTestCache_1.createMongoTestCache; } });
|
|
6
11
|
var setTerrenoTestEnv_1 = require("./env/setTerrenoTestEnv");
|
|
7
12
|
Object.defineProperty(exports, "setTerrenoTestEnv", { enumerable: true, get: function () { return setTerrenoTestEnv_1.setTerrenoTestEnv; } });
|
|
8
13
|
var authAsUser_1 = require("./http/authAsUser");
|
|
9
14
|
Object.defineProperty(exports, "authAsUser", { enumerable: true, get: function () { return authAsUser_1.authAsUser; } });
|
|
15
|
+
var authWithToken_1 = require("./http/authWithToken");
|
|
16
|
+
Object.defineProperty(exports, "authWithToken", { enumerable: true, get: function () { return authWithToken_1.authWithToken; } });
|
|
10
17
|
var getBaseServer_1 = require("./http/getBaseServer");
|
|
11
18
|
Object.defineProperty(exports, "getBaseServer", { enumerable: true, get: function () { return getBaseServer_1.getBaseServer; } });
|
|
12
19
|
var silenceLogs_1 = require("./logging/silenceLogs");
|
|
13
20
|
Object.defineProperty(exports, "createLogSilencer", { enumerable: true, get: function () { return silenceLogs_1.createLogSilencer; } });
|
|
14
21
|
Object.defineProperty(exports, "registerLogSilencing", { enumerable: true, get: function () { return silenceLogs_1.registerLogSilencing; } });
|
|
22
|
+
var aiSdk_1 = require("./mocks/aiSdk");
|
|
23
|
+
Object.defineProperty(exports, "createMockLanguageModel", { enumerable: true, get: function () { return aiSdk_1.createMockLanguageModel; } });
|
|
24
|
+
Object.defineProperty(exports, "mockLanguageModelStreamParts", { enumerable: true, get: function () { return aiSdk_1.mockLanguageModelStreamParts; } });
|
|
25
|
+
var cloudTasks_1 = require("./mocks/cloudTasks");
|
|
26
|
+
Object.defineProperty(exports, "decodeCloudTaskBody", { enumerable: true, get: function () { return cloudTasks_1.decodeCloudTaskBody; } });
|
|
27
|
+
Object.defineProperty(exports, "registerCloudTasksMock", { enumerable: true, get: function () { return cloudTasks_1.registerCloudTasksMock; } });
|
|
28
|
+
var expoPush_1 = require("./mocks/expoPush");
|
|
29
|
+
Object.defineProperty(exports, "registerExpoPushMock", { enumerable: true, get: function () { return expoPush_1.registerExpoPushMock; } });
|
|
30
|
+
var gcs_1 = require("./mocks/gcs");
|
|
31
|
+
Object.defineProperty(exports, "registerGcsMock", { enumerable: true, get: function () { return gcs_1.registerGcsMock; } });
|
|
32
|
+
var googleAuth_1 = require("./mocks/googleAuth");
|
|
33
|
+
Object.defineProperty(exports, "registerGoogleAuthMock", { enumerable: true, get: function () { return googleAuth_1.registerGoogleAuthMock; } });
|
|
34
|
+
var notifiers_1 = require("./mocks/notifiers");
|
|
35
|
+
Object.defineProperty(exports, "registerTerrenoNotifierMocks", { enumerable: true, get: function () { return notifiers_1.registerTerrenoNotifierMocks; } });
|
|
36
|
+
var sendgrid_1 = require("./mocks/sendgrid");
|
|
37
|
+
Object.defineProperty(exports, "registerSendGridMock", { enumerable: true, get: function () { return sendgrid_1.registerSendGridMock; } });
|
|
15
38
|
var sentryBun_1 = require("./mocks/sentryBun");
|
|
16
39
|
Object.defineProperty(exports, "registerSentryBunMock", { enumerable: true, get: function () { return sentryBun_1.registerSentryBunMock; } });
|
|
40
|
+
var twilio_1 = require("./mocks/twilio");
|
|
41
|
+
Object.defineProperty(exports, "registerTwilioMock", { enumerable: true, get: function () { return twilio_1.registerTwilioMock; } });
|
|
17
42
|
var connection_1 = require("./mongo/connection");
|
|
18
43
|
Object.defineProperty(exports, "buildDatabaseUri", { enumerable: true, get: function () { return connection_1.buildDatabaseUri; } });
|
|
19
44
|
Object.defineProperty(exports, "DEFAULT_LOCAL_MONGO_URI", { enumerable: true, get: function () { return connection_1.DEFAULT_LOCAL_MONGO_URI; } });
|
|
@@ -32,12 +57,16 @@ Object.defineProperty(exports, "waitForDatabaseReady", { enumerable: true, get:
|
|
|
32
57
|
var registerBackendPreload_1 = require("./preload/registerBackendPreload");
|
|
33
58
|
Object.defineProperty(exports, "registerBackendPreload", { enumerable: true, get: function () { return registerBackendPreload_1.registerBackendPreload; } });
|
|
34
59
|
Object.defineProperty(exports, "registerSimpleMongoPreload", { enumerable: true, get: function () { return registerBackendPreload_1.registerSimpleMongoPreload; } });
|
|
60
|
+
var freezeTime_1 = require("./time/freezeTime");
|
|
61
|
+
Object.defineProperty(exports, "freezeTime", { enumerable: true, get: function () { return freezeTime_1.freezeTime; } });
|
|
35
62
|
var testTransaction_1 = require("./transaction/testTransaction");
|
|
36
63
|
Object.defineProperty(exports, "abortTestTransaction", { enumerable: true, get: function () { return testTransaction_1.abortTestTransaction; } });
|
|
37
64
|
Object.defineProperty(exports, "getTestSession", { enumerable: true, get: function () { return testTransaction_1.getTestSession; } });
|
|
38
65
|
Object.defineProperty(exports, "installTransactionPatches", { enumerable: true, get: function () { return testTransaction_1.installTransactionPatches; } });
|
|
66
|
+
Object.defineProperty(exports, "isTestTransactionOperationCancelled", { enumerable: true, get: function () { return testTransaction_1.isTestTransactionOperationCancelled; } });
|
|
39
67
|
Object.defineProperty(exports, "resetTestSessionAfterReconnect", { enumerable: true, get: function () { return testTransaction_1.resetTestSessionAfterReconnect; } });
|
|
40
68
|
Object.defineProperty(exports, "startTestTransaction", { enumerable: true, get: function () { return testTransaction_1.startTestTransaction; } });
|
|
69
|
+
Object.defineProperty(exports, "TestTransactionOperationCancelledError", { enumerable: true, get: function () { return testTransaction_1.TestTransactionOperationCancelledError; } });
|
|
41
70
|
var ensureAllIndexes_1 = require("./utils/ensureAllIndexes");
|
|
42
71
|
Object.defineProperty(exports, "ensureAllIndexes", { enumerable: true, get: function () { return ensureAllIndexes_1.ensureAllIndexes; } });
|
|
43
72
|
var timeout_1 = require("./utils/timeout");
|
|
@@ -45,3 +74,6 @@ Object.defineProperty(exports, "timeout", { enumerable: true, get: function () {
|
|
|
45
74
|
var waitForDocuments_1 = require("./utils/waitForDocuments");
|
|
46
75
|
Object.defineProperty(exports, "waitForDocument", { enumerable: true, get: function () { return waitForDocuments_1.waitForDocument; } });
|
|
47
76
|
Object.defineProperty(exports, "waitForDocuments", { enumerable: true, get: function () { return waitForDocuments_1.waitForDocuments; } });
|
|
77
|
+
var waitUntil_1 = require("./utils/waitUntil");
|
|
78
|
+
Object.defineProperty(exports, "waitForCalls", { enumerable: true, get: function () { return waitUntil_1.waitForCalls; } });
|
|
79
|
+
Object.defineProperty(exports, "waitUntil", { enumerable: true, get: function () { return waitUntil_1.waitUntil; } });
|
|
@@ -12,8 +12,6 @@ const winston_1 = __importDefault(require("winston"));
|
|
|
12
12
|
const getApiWinstonLogger = () => {
|
|
13
13
|
try {
|
|
14
14
|
// Runtime-only so @terreno/test compiles without @terreno/api.
|
|
15
|
-
// noExplicitAny: optional peer resolved at preload time
|
|
16
|
-
// biome-ignore lint/suspicious/noExplicitAny: optional peer resolved at preload time
|
|
17
15
|
const api = require("@terreno/api");
|
|
18
16
|
return api.winstonLogger;
|
|
19
17
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Mock } from "bun:test";
|
|
2
|
+
export type MockLanguageModelFinishReason = "stop" | "length" | "content-filter" | "tool-calls" | "error" | "other" | "unknown";
|
|
3
|
+
export interface MockLanguageModelUsage {
|
|
4
|
+
inputTokens: number;
|
|
5
|
+
outputTokens: number;
|
|
6
|
+
totalTokens: number;
|
|
7
|
+
}
|
|
8
|
+
export interface MockLanguageModelToolCall {
|
|
9
|
+
/** Tool input; serialized to the JSON string the provider spec expects. */
|
|
10
|
+
input: unknown;
|
|
11
|
+
/** Default `call_<n>` (1-based across the response's calls). */
|
|
12
|
+
toolCallId?: string;
|
|
13
|
+
toolName: string;
|
|
14
|
+
}
|
|
15
|
+
/** One scripted model turn. Each `doGenerate`/`doStream` call consumes the next one. */
|
|
16
|
+
export interface MockLanguageModelResponse {
|
|
17
|
+
/** Stream deltas. Default `[text]`. `doGenerate` returns `text`, or the joined chunks. */
|
|
18
|
+
chunks?: string[];
|
|
19
|
+
/** Makes the call fail: `doGenerate` rejects, `doStream` errors after the text deltas. */
|
|
20
|
+
error?: string;
|
|
21
|
+
/** Default `"tool-calls"` when `toolCalls` is set, otherwise `"stop"`. */
|
|
22
|
+
finishReason?: MockLanguageModelFinishReason;
|
|
23
|
+
text?: string;
|
|
24
|
+
toolCalls?: MockLanguageModelToolCall[];
|
|
25
|
+
usage?: MockLanguageModelUsage;
|
|
26
|
+
}
|
|
27
|
+
export interface MockLanguageModelStreamPart {
|
|
28
|
+
type: string;
|
|
29
|
+
[key: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
export interface MockLanguageModelGenerateResult {
|
|
32
|
+
content: Array<{
|
|
33
|
+
text: string;
|
|
34
|
+
type: "text";
|
|
35
|
+
} | {
|
|
36
|
+
input: string;
|
|
37
|
+
toolCallId: string;
|
|
38
|
+
toolName: string;
|
|
39
|
+
type: "tool-call";
|
|
40
|
+
}>;
|
|
41
|
+
finishReason: MockLanguageModelFinishReason;
|
|
42
|
+
usage: MockLanguageModelUsage;
|
|
43
|
+
warnings: never[];
|
|
44
|
+
}
|
|
45
|
+
export interface CreateMockLanguageModelOptions {
|
|
46
|
+
modelId?: string;
|
|
47
|
+
provider?: string;
|
|
48
|
+
/** Scripted turns, in order. The last one repeats once the script runs out. */
|
|
49
|
+
responses?: MockLanguageModelResponse[];
|
|
50
|
+
/** Shorthand for `responses: [{text}]`. Default `"Mock response"`. */
|
|
51
|
+
text?: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A Vercel AI SDK `LanguageModelV2` (spec `"v2"`, which AI SDK 5 and 6 accept) for passing
|
|
55
|
+
* straight to `AIService`, `streamText`, or `generateText`. Assert on `doGenerate.mock.calls` /
|
|
56
|
+
* `doStream.mock.calls` to see the prompt and tools the SDK sent.
|
|
57
|
+
*/
|
|
58
|
+
export interface MockLanguageModel {
|
|
59
|
+
doGenerate: Mock<(options: unknown) => Promise<MockLanguageModelGenerateResult>>;
|
|
60
|
+
doStream: Mock<(options: unknown) => Promise<{
|
|
61
|
+
stream: ReadableStream<MockLanguageModelStreamPart>;
|
|
62
|
+
}>>;
|
|
63
|
+
readonly modelId: string;
|
|
64
|
+
readonly provider: string;
|
|
65
|
+
/** Clears calls and overrides and restarts the script at the first response. */
|
|
66
|
+
reset: () => void;
|
|
67
|
+
readonly specificationVersion: "v2";
|
|
68
|
+
readonly supportedUrls: Record<string, RegExp[]>;
|
|
69
|
+
}
|
|
70
|
+
/** Builds the `LanguageModelV2` stream parts a response produces. */
|
|
71
|
+
export declare const mockLanguageModelStreamParts: (response: MockLanguageModelResponse) => MockLanguageModelStreamPart[];
|
|
72
|
+
/**
|
|
73
|
+
* Creates a scripted mock language model. Prefer this to `mock.module("ai", ...)`: the real AI SDK
|
|
74
|
+
* runs, so tool loops, structured output, and streaming behave as in production. Needs no `ai`
|
|
75
|
+
* install. For full-spec V3 fidelity, `MockLanguageModelV3` from `ai/test` is the SDK's own.
|
|
76
|
+
*/
|
|
77
|
+
export declare const createMockLanguageModel: (options?: CreateMockLanguageModelOptions) => MockLanguageModel;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMockLanguageModel = exports.mockLanguageModelStreamParts = void 0;
|
|
4
|
+
const mockGroup_1 = require("./mockGroup");
|
|
5
|
+
const DEFAULT_USAGE = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
|
|
6
|
+
const toolCallParts = (toolCalls) => (toolCalls ?? []).map((call, index) => ({
|
|
7
|
+
input: JSON.stringify(call.input ?? {}),
|
|
8
|
+
toolCallId: call.toolCallId ?? `call_${index + 1}`,
|
|
9
|
+
toolName: call.toolName,
|
|
10
|
+
type: "tool-call",
|
|
11
|
+
}));
|
|
12
|
+
const finishReasonFor = (response) => response.finishReason ?? (response.toolCalls?.length ? "tool-calls" : "stop");
|
|
13
|
+
/** Builds the `LanguageModelV2` stream parts a response produces. */
|
|
14
|
+
const mockLanguageModelStreamParts = (response) => {
|
|
15
|
+
const chunks = response.chunks ?? (response.text ? [response.text] : []);
|
|
16
|
+
const textParts = chunks.length === 0
|
|
17
|
+
? []
|
|
18
|
+
: [
|
|
19
|
+
{ id: "text-1", type: "text-start" },
|
|
20
|
+
...chunks.map((delta) => ({ delta, id: "text-1", type: "text-delta" })),
|
|
21
|
+
{ id: "text-1", type: "text-end" },
|
|
22
|
+
];
|
|
23
|
+
return [
|
|
24
|
+
{ type: "stream-start", warnings: [] },
|
|
25
|
+
...textParts,
|
|
26
|
+
...toolCallParts(response.toolCalls),
|
|
27
|
+
{
|
|
28
|
+
finishReason: finishReasonFor(response),
|
|
29
|
+
type: "finish",
|
|
30
|
+
usage: response.usage ?? DEFAULT_USAGE,
|
|
31
|
+
},
|
|
32
|
+
];
|
|
33
|
+
};
|
|
34
|
+
exports.mockLanguageModelStreamParts = mockLanguageModelStreamParts;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a scripted mock language model. Prefer this to `mock.module("ai", ...)`: the real AI SDK
|
|
37
|
+
* runs, so tool loops, structured output, and streaming behave as in production. Needs no `ai`
|
|
38
|
+
* install. For full-spec V3 fidelity, `MockLanguageModelV3` from `ai/test` is the SDK's own.
|
|
39
|
+
*/
|
|
40
|
+
const createMockLanguageModel = (options = {}) => {
|
|
41
|
+
const responses = options.responses?.length
|
|
42
|
+
? options.responses
|
|
43
|
+
: [{ text: options.text ?? "Mock response" }];
|
|
44
|
+
const group = (0, mockGroup_1.createMockGroup)();
|
|
45
|
+
let callCount = 0;
|
|
46
|
+
const nextResponse = () => {
|
|
47
|
+
const response = responses[Math.min(callCount, responses.length - 1)];
|
|
48
|
+
callCount += 1;
|
|
49
|
+
return response;
|
|
50
|
+
};
|
|
51
|
+
const doGenerate = group.fn(async (_options) => {
|
|
52
|
+
const response = nextResponse();
|
|
53
|
+
if (response.error) {
|
|
54
|
+
throw new Error(response.error);
|
|
55
|
+
}
|
|
56
|
+
const text = response.text ?? response.chunks?.join("");
|
|
57
|
+
return {
|
|
58
|
+
content: [
|
|
59
|
+
...(text ? [{ text, type: "text" }] : []),
|
|
60
|
+
...toolCallParts(response.toolCalls),
|
|
61
|
+
],
|
|
62
|
+
finishReason: finishReasonFor(response),
|
|
63
|
+
usage: response.usage ?? DEFAULT_USAGE,
|
|
64
|
+
warnings: [],
|
|
65
|
+
};
|
|
66
|
+
});
|
|
67
|
+
const doStream = group.fn(async (_options) => {
|
|
68
|
+
const response = nextResponse();
|
|
69
|
+
const parts = (0, exports.mockLanguageModelStreamParts)(response);
|
|
70
|
+
let index = 0;
|
|
71
|
+
// Pull one part at a time so parts before a scripted error still reach the reader.
|
|
72
|
+
const stream = new ReadableStream({
|
|
73
|
+
pull: (controller) => {
|
|
74
|
+
const part = parts[index];
|
|
75
|
+
index += 1;
|
|
76
|
+
if (!part) {
|
|
77
|
+
controller.close();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (response.error && part.type !== "stream-start" && !part.type.startsWith("text")) {
|
|
81
|
+
controller.error(new Error(response.error));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
controller.enqueue(part);
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
return { stream };
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
doGenerate,
|
|
91
|
+
doStream,
|
|
92
|
+
modelId: options.modelId ?? "mock-model",
|
|
93
|
+
provider: options.provider ?? "mock-provider",
|
|
94
|
+
reset: () => {
|
|
95
|
+
group.reset();
|
|
96
|
+
callCount = 0;
|
|
97
|
+
},
|
|
98
|
+
specificationVersion: "v2",
|
|
99
|
+
supportedUrls: {},
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
exports.createMockLanguageModel = createMockLanguageModel;
|