@tailor-platform/sdk 2.3.0 → 2.5.0
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 +171 -0
- package/README.md +1 -1
- package/dist/aigateway-DsWDjzk4.mjs +2 -0
- package/dist/{aigateway-DR4Kwuik.mjs.map → aigateway-DsWDjzk4.mjs.map} +1 -1
- package/dist/application-DFOUovmN.mjs +1 -0
- package/dist/application-D_4vg1KR.mjs +192 -0
- package/dist/application-D_4vg1KR.mjs.map +1 -0
- package/dist/assert-WeXvmG4j.mjs +2 -0
- package/dist/{assert-DBxo8jPo.mjs.map → assert-WeXvmG4j.mjs.map} +1 -1
- package/dist/authconnection-CynFBIv8.mjs +2 -0
- package/dist/{authconnection-CZvi9ANm.mjs.map → authconnection-CynFBIv8.mjs.map} +1 -1
- package/dist/brand-C8nMKhJC.mjs +2 -0
- package/dist/{brand-Eo4pLXPJ.mjs.map → brand-C8nMKhJC.mjs.map} +1 -1
- package/dist/cli/commands/deploy/deploy.d.mts +2 -2
- package/dist/cli/commands/deploy/deployment-target.d.mts +2 -0
- package/dist/cli/commands/deploy/event-subscriptions.d.mts +3 -0
- package/dist/cli/commands/deploy/tailordb/apply.d.mts +3 -0
- package/dist/cli/commands/deploy/tailordb/index.d.mts +3 -10
- package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +5 -0
- package/dist/cli/commands/deploy/tailordb/plan.d.mts +8 -0
- package/dist/cli/commands/executor/jobs.d.mts +1 -1
- package/dist/cli/commands/generate/seed/bundler.d.mts +2 -2
- package/dist/cli/commands/show.d.mts +1 -1
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +15 -15
- package/dist/cli/commands/tailordb/migrate/generate.d.mts +7 -3
- package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +1 -1
- package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +43 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +62 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-local.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-migrations.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-remote.d.mts +1 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +3 -1
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +5 -117
- package/dist/cli/commands/tailordb/truncate.d.mts +2 -2
- package/dist/cli/lib.d.mts +8 -4
- package/dist/cli/lib.mjs +1 -9
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +1170 -7686
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/seed-chunker.d.mts +5 -5
- package/dist/cli/ts-hook.mjs +3 -1
- package/dist/completion/zsh-worker.zsh +99 -18
- package/dist/configure/config/index.d.mts +2 -2
- package/dist/configure/config/types.d.mts +2 -2
- package/dist/configure/index.d.mts +49 -12
- package/dist/configure/index.mjs +1 -1267
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/aigateway/index.d.mts +5 -4
- package/dist/configure/services/aigateway/types.d.mts +6 -1
- package/dist/configure/services/auth/types.d.mts +3 -3
- package/dist/configure/services/idp/types.d.mts +1 -1
- package/dist/configure/services/tailordb/permission.d.mts +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +5 -9
- package/dist/configure/services/tailordb/types.d.mts +8 -5
- package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
- package/dist/configure/services/workflow/job.d.mts +12 -2
- package/dist/configure/types/auth-namespace-name.d.mts +18 -0
- package/dist/configure/types/field.types.d.mts +1 -1
- package/dist/configure/types/permission-operand.types.d.mts +1 -1
- package/dist/context-D0QjfxzD.mjs +2 -0
- package/dist/{context-DYQVYWqZ.mjs.map → context-D0QjfxzD.mjs.map} +1 -1
- package/dist/crashreport-B-_HTKLr.mjs +42 -0
- package/dist/{crashreport-CIIfLnoO.mjs.map → crashreport-B-_HTKLr.mjs.map} +1 -1
- package/dist/crashreport-BmsRIdpy.mjs +1 -0
- package/dist/errors-DSEXKRVD.mjs +2 -0
- package/dist/errors-DSEXKRVD.mjs.map +1 -0
- package/dist/file-COPYfju_.mjs +2 -0
- package/dist/file-COPYfju_.mjs.map +1 -0
- package/dist/globals-CMHSnj4w.mjs +2 -0
- package/dist/{globals-B2nlxBrz.mjs.map → globals-CMHSnj4w.mjs.map} +1 -1
- package/dist/iconv-DlFMt2gW.mjs +2 -0
- package/dist/{iconv-QWaZh0TT.mjs.map → iconv-DlFMt2gW.mjs.map} +1 -1
- package/dist/idp-G_ojPBB5.mjs +2 -0
- package/dist/{idp-RA_swu-h.mjs.map → idp-G_ojPBB5.mjs.map} +1 -1
- package/dist/interceptor-DQg3cR_9.mjs +2 -0
- package/dist/{interceptor-e33JtsC-.mjs.map → interceptor-DQg3cR_9.mjs.map} +1 -1
- package/dist/kysely/index.mjs +1 -31
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/kysely-type-BTi3BMtL.mjs +43 -0
- package/dist/kysely-type-BTi3BMtL.mjs.map +1 -0
- package/dist/logger-BcGy-u7G.mjs +9 -0
- package/dist/{logger-DSdExfor.mjs.map → logger-BcGy-u7G.mjs.map} +1 -1
- package/dist/logger-DP2BjQ93.mjs +2 -0
- package/dist/{logger-BtX0suGY.mjs.map → logger-DP2BjQ93.mjs.map} +1 -1
- package/dist/multiline-EyzjEwn9.mjs +3 -0
- package/dist/{multiline-sfHpTZZK.mjs.map → multiline-EyzjEwn9.mjs.map} +1 -1
- package/dist/node-builtins-oBl7EbyV.mjs +2 -0
- package/dist/{node-builtins-CmaL2Cbq.mjs.map → node-builtins-oBl7EbyV.mjs.map} +1 -1
- package/dist/package-json-C690ceex.mjs +2 -0
- package/dist/{package-json-8b0O9TlX.mjs.map → package-json-C690ceex.mjs.map} +1 -1
- package/dist/package-json-CmqhDJ__.mjs +1 -0
- package/dist/parser/service/tailordb/type-source.d.mts +5 -5
- package/dist/parser/service/tailordb/types.d.mts +4 -4
- package/dist/platform-serialize-DkiTdHOt.mjs +2 -0
- package/dist/{platform-serialize-RoRtBS0v.mjs.map → platform-serialize-DkiTdHOt.mjs.map} +1 -1
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +5 -114
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +22 -101
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +9 -2
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -275
- package/dist/plugin/builtin/seed/index.d.mts +5 -0
- package/dist/plugin/builtin/seed/index.mjs +1 -3
- package/dist/plugin/builtin/seed/seed-type-processor.d.mts +4 -6
- package/dist/plugin/get-generated-table.d.mts +16 -0
- package/dist/plugin/index.d.mts +3 -2
- package/dist/plugin/index.mjs +1 -251
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/types.d.mts +32 -25
- package/dist/plugin/with-context.d.mts +4 -4
- package/dist/register-ts-hook-Drnaproy.mjs +640 -0
- package/dist/register-ts-hook-Drnaproy.mjs.map +1 -0
- package/dist/registry-HlEaGvl5.mjs +2 -0
- package/dist/{registry-BIGVUrMB.mjs.map → registry-HlEaGvl5.mjs.map} +1 -1
- package/dist/repl-editor-BG1aDOfH.mjs +2 -0
- package/dist/{repl-editor-BCozyiNq.mjs.map → repl-editor-BG1aDOfH.mjs.map} +1 -1
- package/dist/runtime/aigateway.mjs +1 -3
- package/dist/runtime/authconnection.mjs +1 -3
- package/dist/runtime/context.mjs +1 -3
- package/dist/runtime/file.d.mts +28 -28
- package/dist/runtime/file.mjs +1 -3
- package/dist/runtime/globals.mjs +1 -1
- package/dist/runtime/iconv.mjs +1 -3
- package/dist/runtime/idp.mjs +1 -3
- package/dist/runtime/index.mjs +1 -11
- package/dist/runtime/logger.mjs +1 -3
- package/dist/runtime/secretmanager.mjs +1 -3
- package/dist/runtime/types.d.mts +1 -1
- package/dist/runtime/workflow.mjs +1 -3
- package/dist/schema-Ze_dI5VX.mjs +2 -0
- package/dist/schema-Ze_dI5VX.mjs.map +1 -0
- package/dist/secret-file-C9wp_FCX.mjs +2 -0
- package/dist/{secret-file-C3J4Gy8r.mjs.map → secret-file-C9wp_FCX.mjs.map} +1 -1
- package/dist/secretmanager-5olfnI1b.mjs +2 -0
- package/dist/{secretmanager-IY4UvinW.mjs.map → secretmanager-5olfnI1b.mjs.map} +1 -1
- package/dist/secretmanager-vHQoXdQz.mjs +2 -0
- package/dist/{secretmanager-CYlpffsz.mjs.map → secretmanager-vHQoXdQz.mjs.map} +1 -1
- package/dist/seed/index.d.mts +4 -4
- package/dist/seed/index.mjs +8 -244
- package/dist/seed/index.mjs.map +1 -1
- package/dist/seed-DwqRFdqP.mjs +207 -0
- package/dist/seed-DwqRFdqP.mjs.map +1 -0
- package/dist/service-BVe9u2Rt.mjs +7 -0
- package/dist/service-BVe9u2Rt.mjs.map +1 -0
- package/dist/service-CpZELSBa.mjs +1 -0
- package/dist/service-DlgaUO4V.mjs +2 -0
- package/dist/{service-hZskxZmg.mjs.map → service-DlgaUO4V.mjs.map} +1 -1
- package/dist/service_pb-DGKCLuAs.mjs +2 -0
- package/dist/{service_pb-BEWj1pOV.mjs.map → service_pb-DGKCLuAs.mjs.map} +1 -1
- package/dist/service_pb-_aeFE-Nv.mjs +1 -0
- package/dist/telemetry-Bklv9kQY.mjs +2 -0
- package/dist/{telemetry-BRVdwh14.mjs.map → telemetry-Bklv9kQY.mjs.map} +1 -1
- package/dist/telemetry-DXHP3VVi.mjs +1 -0
- package/dist/type-source--ZNcV8RJ.mjs +2 -0
- package/dist/type-source--ZNcV8RJ.mjs.map +1 -0
- package/dist/types/aigateway.generated.d.mts +2 -2
- package/dist/types/auth.generated.d.mts +3 -3
- package/dist/types/executor.generated.d.mts +2 -2
- package/dist/types/tailordb.generated.d.mts +12 -12
- package/dist/user-agent-vdHYF3QL.mjs +2 -0
- package/dist/{user-agent-Bgsszb5I.mjs.map → user-agent-vdHYF3QL.mjs.map} +1 -1
- package/dist/utils/test/index.d.mts +4 -4
- package/dist/utils/test/index.mjs +1 -109
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -41
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.mjs +1 -1980
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/file.d.mts +8 -8
- package/dist/vitest/setup.mjs +1 -140
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/wait-point-invoker-eiP-IIux.mjs +2 -0
- package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -0
- package/dist/wait-point-registry-BrkwfyjS.mjs +2 -0
- package/dist/{wait-point-registry-TL99zotw.mjs.map → wait-point-registry-BrkwfyjS.mjs.map} +1 -1
- package/dist/workflow-Cs9ISw6j.mjs +2 -0
- package/dist/{workflow-Bamae_Yc.mjs.map → workflow-Cs9ISw6j.mjs.map} +1 -1
- package/dist/workspace_resource_pb--GeYQPXu.mjs +2 -0
- package/dist/{workspace_resource_pb-HNIL_Vfj.mjs.map → workspace_resource_pb--GeYQPXu.mjs.map} +1 -1
- package/docs/cli/application.md +3 -1
- package/docs/cli/function.md +77 -13
- package/docs/cli/setup.md +24 -14
- package/docs/cli/tailordb.md +32 -30
- package/docs/cli/workspace.md +2 -2
- package/docs/cli-reference.md +23 -22
- package/docs/configuration.md +2 -2
- package/docs/github-actions.md +10 -9
- package/docs/migration/v2.md +16 -4
- package/docs/migration/v3.md +123 -0
- package/docs/plugin/custom.md +130 -85
- package/docs/plugin/index.md +3 -3
- package/docs/quickstart.md +1 -1
- package/docs/services/aigateway.md +33 -9
- package/docs/services/executor.md +5 -1
- package/docs/services/tailordb-migration.md +68 -54
- package/docs/services/tailordb.md +7 -7
- package/docs/services/workflow.md +10 -9
- package/docs/testing.md +1 -1
- package/package.json +16 -16
- package/postinstall.mjs +1 -1
- package/dist/aigateway-DR4Kwuik.mjs +0 -9
- package/dist/application-BZfk4HKm.mjs +0 -3
- package/dist/application-F-nl107y.mjs +0 -6019
- package/dist/application-F-nl107y.mjs.map +0 -1
- package/dist/assert-DBxo8jPo.mjs +0 -9
- package/dist/authconnection-CZvi9ANm.mjs +0 -9
- package/dist/brand-Eo4pLXPJ.mjs +0 -36
- package/dist/context-DYQVYWqZ.mjs +0 -23
- package/dist/crashreport-CIIfLnoO.mjs +0 -423
- package/dist/crashreport-CINZ5dVN.mjs +0 -3
- package/dist/errors-BVb6vYGy.mjs +0 -89
- package/dist/errors-BVb6vYGy.mjs.map +0 -1
- package/dist/file-BUcmVIH2.mjs +0 -58
- package/dist/file-BUcmVIH2.mjs.map +0 -1
- package/dist/globals-B2nlxBrz.mjs +0 -126
- package/dist/iconv-QWaZh0TT.mjs +0 -38
- package/dist/idp-RA_swu-h.mjs +0 -82
- package/dist/interceptor-e33JtsC-.mjs +0 -33
- package/dist/logger-BtX0suGY.mjs +0 -48
- package/dist/logger-DSdExfor.mjs +0 -358
- package/dist/multiline-sfHpTZZK.mjs +0 -38
- package/dist/node-builtins-CmaL2Cbq.mjs +0 -36
- package/dist/package-json-8b0O9TlX.mjs +0 -17
- package/dist/package-json-Cv2Z-TqQ.mjs +0 -3
- package/dist/platform-serialize-RoRtBS0v.mjs +0 -46
- package/dist/plugin/builtin/kysely-type/index.mjs.map +0 -1
- package/dist/plugin/builtin/seed/types.d.mts +0 -2
- package/dist/plugin/get-generated-type.d.mts +0 -16
- package/dist/register-ts-hook-ClI226n2.mjs +0 -25543
- package/dist/register-ts-hook-ClI226n2.mjs.map +0 -1
- package/dist/registry-BIGVUrMB.mjs +0 -54
- package/dist/repl-editor-BCozyiNq.mjs +0 -251
- package/dist/schema--xYWRGfe.mjs +0 -639
- package/dist/schema--xYWRGfe.mjs.map +0 -1
- package/dist/secret-file-C3J4Gy8r.mjs +0 -64
- package/dist/secretmanager-CYlpffsz.mjs +0 -13
- package/dist/secretmanager-IY4UvinW.mjs +0 -131
- package/dist/seed-xqM9WIHP.mjs +0 -483
- package/dist/seed-xqM9WIHP.mjs.map +0 -1
- package/dist/service-C_WpbKHu.mjs +0 -898
- package/dist/service-C_WpbKHu.mjs.map +0 -1
- package/dist/service-D1RCdzIL.mjs +0 -3
- package/dist/service-hZskxZmg.mjs +0 -131
- package/dist/service_pb-BEWj1pOV.mjs +0 -167
- package/dist/service_pb-BjlhvK9E.mjs +0 -3
- package/dist/telemetry-BRVdwh14.mjs +0 -84
- package/dist/telemetry-CkbkeJxl.mjs +0 -3
- package/dist/type-source-DH_LH20p.mjs +0 -13
- package/dist/type-source-DH_LH20p.mjs.map +0 -1
- package/dist/user-agent-Bgsszb5I.mjs +0 -28
- package/dist/wait-point-invoker-__oE88_P.mjs +0 -148
- package/dist/wait-point-invoker-__oE88_P.mjs.map +0 -1
- package/dist/wait-point-registry-TL99zotw.mjs +0 -47
- package/dist/workflow-Bamae_Yc.mjs +0 -34
- package/dist/workspace_resource_pb-HNIL_Vfj.mjs +0 -860
package/dist/vitest/index.mjs
CHANGED
|
@@ -1,1981 +1,2 @@
|
|
|
1
|
-
import { i as getRegisteredJob, t as START_DEFAULT } from "../registry-BIGVUrMB.mjs";
|
|
2
|
-
import { a as getWaitPointKey, c as readWorkflowTestEnv, i as getWaitPointInvoker, o as buildJobContext, s as clearWorkflowTestEnv, u as writeWorkflowTestEnv } from "../wait-point-invoker-__oE88_P.mjs";
|
|
3
|
-
import { t as assertDefined } from "../assert-DBxo8jPo.mjs";
|
|
4
|
-
import { n as isNodeBuiltinImport, t as getNodeBuiltinMessage } from "../node-builtins-CmaL2Cbq.mjs";
|
|
5
|
-
import { t as platformSerialize } from "../platform-serialize-RoRtBS0v.mjs";
|
|
6
|
-
import { i as withDispose, n as tailorRoot, r as tailordbRoot, t as mockSecretmanager } from "../secretmanager-IY4UvinW.mjs";
|
|
7
|
-
import { isEqual } from "es-toolkit";
|
|
8
|
-
import { fileURLToPath } from "node:url";
|
|
9
|
-
import { ColumnNode, CompiledQuery, InsertQueryNode, Kysely, PostgresAdapter, PostgresIntrospector, PostgresQueryCompiler, PrimitiveValueListNode, ReferenceNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode } from "kysely";
|
|
10
|
-
import { dirname, isAbsolute, matchesGlob, relative, resolve } from "node:path";
|
|
11
|
-
import { vi } from "vitest";
|
|
12
|
-
|
|
13
|
-
//#region src/vitest/blocked-modules.ts
|
|
14
|
-
/**
|
|
15
|
-
* Check if a module specifier is a blocked Node.js built-in.
|
|
16
|
-
* @param specifier - Module specifier to check (e.g. "node:crypto", "fs")
|
|
17
|
-
* @returns Whether the specifier is blocked
|
|
18
|
-
*/
|
|
19
|
-
function isBlockedModule(specifier) {
|
|
20
|
-
return isNodeBuiltinImport(specifier);
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Get the error message for a blocked module import.
|
|
24
|
-
* @param specifier - Module specifier that was blocked
|
|
25
|
-
* @returns Error message with optional suggestion for the Web Standard API alternative
|
|
26
|
-
*/
|
|
27
|
-
function getBlockedMessage(specifier) {
|
|
28
|
-
return getNodeBuiltinMessage(specifier);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
//#endregion
|
|
32
|
-
//#region src/vitest/plugin.ts
|
|
33
|
-
const DEFAULT_TEST_INCLUDE = ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"];
|
|
34
|
-
const IMPORT_LIKE_TYPES = /* @__PURE__ */ new Set([
|
|
35
|
-
"ImportDeclaration",
|
|
36
|
-
"ExportNamedDeclaration",
|
|
37
|
-
"ExportAllDeclaration"
|
|
38
|
-
]);
|
|
39
|
-
const UNSAFE_BINDING_NAMES = /* @__PURE__ */ new Set([
|
|
40
|
-
"break",
|
|
41
|
-
"case",
|
|
42
|
-
"catch",
|
|
43
|
-
"class",
|
|
44
|
-
"const",
|
|
45
|
-
"continue",
|
|
46
|
-
"debugger",
|
|
47
|
-
"default",
|
|
48
|
-
"delete",
|
|
49
|
-
"do",
|
|
50
|
-
"else",
|
|
51
|
-
"enum",
|
|
52
|
-
"export",
|
|
53
|
-
"extends",
|
|
54
|
-
"false",
|
|
55
|
-
"finally",
|
|
56
|
-
"for",
|
|
57
|
-
"function",
|
|
58
|
-
"if",
|
|
59
|
-
"import",
|
|
60
|
-
"in",
|
|
61
|
-
"instanceof",
|
|
62
|
-
"new",
|
|
63
|
-
"null",
|
|
64
|
-
"return",
|
|
65
|
-
"super",
|
|
66
|
-
"switch",
|
|
67
|
-
"this",
|
|
68
|
-
"throw",
|
|
69
|
-
"true",
|
|
70
|
-
"try",
|
|
71
|
-
"typeof",
|
|
72
|
-
"var",
|
|
73
|
-
"void",
|
|
74
|
-
"while",
|
|
75
|
-
"with",
|
|
76
|
-
"yield",
|
|
77
|
-
"let",
|
|
78
|
-
"static",
|
|
79
|
-
"implements",
|
|
80
|
-
"interface",
|
|
81
|
-
"package",
|
|
82
|
-
"private",
|
|
83
|
-
"protected",
|
|
84
|
-
"public",
|
|
85
|
-
"await",
|
|
86
|
-
"arguments",
|
|
87
|
-
"eval"
|
|
88
|
-
]);
|
|
89
|
-
const ID_START = /^[A-Za-z_$]/;
|
|
90
|
-
const ID_CONT = /^[A-Za-z0-9_$]*$/;
|
|
91
|
-
function isSafeBindingName(name) {
|
|
92
|
-
if (UNSAFE_BINDING_NAMES.has(name)) return false;
|
|
93
|
-
if (name.length === 0) return false;
|
|
94
|
-
const firstChar = name[0];
|
|
95
|
-
if (firstChar === void 0) return false;
|
|
96
|
-
return ID_START.test(firstChar) && ID_CONT.test(name.slice(1));
|
|
97
|
-
}
|
|
98
|
-
function buildBlockedReplacement(node, message) {
|
|
99
|
-
const literal = JSON.stringify(message);
|
|
100
|
-
const throwStmt = `throw new Error(${literal});`;
|
|
101
|
-
const throwExpr = `(() => { throw new Error(${literal}); })()`;
|
|
102
|
-
if (node.type === "ExportNamedDeclaration") {
|
|
103
|
-
const specs = node.specifiers ?? [];
|
|
104
|
-
const stubs = [];
|
|
105
|
-
for (const spec of specs) {
|
|
106
|
-
const exportedName = spec.exported?.name;
|
|
107
|
-
if (typeof exportedName !== "string") continue;
|
|
108
|
-
if (exportedName === "default") {
|
|
109
|
-
stubs.push(`export default ${throwExpr};`);
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
if (!isSafeBindingName(exportedName)) return throwStmt;
|
|
113
|
-
stubs.push(`export const ${exportedName} = ${throwExpr};`);
|
|
114
|
-
}
|
|
115
|
-
return stubs.length > 0 ? stubs.join(" ") : throwStmt;
|
|
116
|
-
}
|
|
117
|
-
if (node.type === "ExportAllDeclaration") {
|
|
118
|
-
const exportedName = node.exported?.name;
|
|
119
|
-
if (typeof exportedName === "string" && isSafeBindingName(exportedName)) return `export const ${exportedName} = ${throwExpr};`;
|
|
120
|
-
return throwStmt;
|
|
121
|
-
}
|
|
122
|
-
return throwStmt;
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Vite plugin that blocks Node.js built-in module imports from production code.
|
|
126
|
-
*
|
|
127
|
-
* Uses the `transform` hook to walk the Rollup-provided AST of non-test source
|
|
128
|
-
* files for static `node:*` imports and re-exports.
|
|
129
|
-
* `ImportDeclaration` and bare `export * from "..."` are replaced with a
|
|
130
|
-
* `throw new Error(...)` statement so the failure surfaces at evaluation time.
|
|
131
|
-
* `ExportNamedDeclaration` (`export { x, y as z } from "..."`) and namespaced
|
|
132
|
-
* `export * as ns from "..."` are rewritten to per-binding stub exports
|
|
133
|
-
* (`export const x = (() => { throw new Error(...) })();`). The IIFE throws
|
|
134
|
-
* eagerly during module evaluation (same timing as a top-level `throw`), but
|
|
135
|
-
* preserving the declared export bindings ensures the surfaced error is the
|
|
136
|
-
* actual "node:* not available" message rather than an opaque
|
|
137
|
-
* "missing export" raised by the loader.
|
|
138
|
-
* Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so
|
|
139
|
-
* source-level transformation is the only reliable interception point.
|
|
140
|
-
* Runs in the default phase (no `enforce: "pre"`) so esbuild's TypeScript
|
|
141
|
-
* transform strips `import type` first; only runtime imports reach this hook.
|
|
142
|
-
* Node.js globals not in the platform runtime are removed by the environment (whitelist-based).
|
|
143
|
-
* Test file patterns are read from the resolved Vitest config (`test.include`).
|
|
144
|
-
* Vitest setup files (`test.setupFiles`) and global-setup files
|
|
145
|
-
* (`test.globalSetup`) are also exempted: they run in the test runner host,
|
|
146
|
-
* not in the emulated platform runtime, so they may freely use `node:*`
|
|
147
|
-
* modules (e.g. `node:url` for `pathToFileURL`).
|
|
148
|
-
* @returns Vite plugin
|
|
149
|
-
*/
|
|
150
|
-
function createBlockPlugin() {
|
|
151
|
-
let isTestFile = () => false;
|
|
152
|
-
let isUserSourceFile = () => false;
|
|
153
|
-
return {
|
|
154
|
-
name: "tailor-runtime-block-node",
|
|
155
|
-
configResolved(config) {
|
|
156
|
-
const testConfig = config.test;
|
|
157
|
-
const root = testConfig?.root ?? config.root;
|
|
158
|
-
const toAbsolutePaths = (value, baseRoot) => (Array.isArray(value) ? value : value ? [value] : []).map((f) => resolve(baseRoot, f));
|
|
159
|
-
const exemptHostFiles = /* @__PURE__ */ new Set([...toAbsolutePaths(testConfig?.setupFiles, root), ...toAbsolutePaths(testConfig?.globalSetup, root)]);
|
|
160
|
-
const includePairs = [{
|
|
161
|
-
root,
|
|
162
|
-
patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE
|
|
163
|
-
}];
|
|
164
|
-
for (const project of testConfig?.projects ?? []) {
|
|
165
|
-
const projectTest = project.test;
|
|
166
|
-
if (!projectTest) continue;
|
|
167
|
-
const projectRoot = projectTest.root ?? root;
|
|
168
|
-
for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) exemptHostFiles.add(f);
|
|
169
|
-
for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) exemptHostFiles.add(f);
|
|
170
|
-
includePairs.push({
|
|
171
|
-
root: projectRoot,
|
|
172
|
-
patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
isTestFile = (id) => {
|
|
176
|
-
if (exemptHostFiles.has(id)) return true;
|
|
177
|
-
return includePairs.some(({ root: r, patterns }) => {
|
|
178
|
-
const candidate = isAbsolute(id) ? relative(r, id) : id;
|
|
179
|
-
return patterns.some((pattern) => matchesGlob(candidate, pattern));
|
|
180
|
-
});
|
|
181
|
-
};
|
|
182
|
-
isUserSourceFile = (id) => {
|
|
183
|
-
if (!isAbsolute(id)) return false;
|
|
184
|
-
const rel = relative(root, id);
|
|
185
|
-
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
186
|
-
};
|
|
187
|
-
},
|
|
188
|
-
transform(code, id) {
|
|
189
|
-
const queryIdx = id.search(/[?#]/);
|
|
190
|
-
const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);
|
|
191
|
-
if (isTestFile(cleanId)) return void 0;
|
|
192
|
-
if (cleanId.includes("node_modules")) return void 0;
|
|
193
|
-
if (!isUserSourceFile(cleanId)) return void 0;
|
|
194
|
-
let ast;
|
|
195
|
-
try {
|
|
196
|
-
ast = this.parse(code);
|
|
197
|
-
} catch {
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
const replacements = [];
|
|
201
|
-
for (const node of ast.body) {
|
|
202
|
-
if (!IMPORT_LIKE_TYPES.has(node.type)) continue;
|
|
203
|
-
const specifier = node.source?.value;
|
|
204
|
-
if (typeof specifier !== "string") continue;
|
|
205
|
-
if (isBlockedModule(specifier)) replacements.push({
|
|
206
|
-
start: node.start,
|
|
207
|
-
end: node.end,
|
|
208
|
-
replacement: buildBlockedReplacement(node, getBlockedMessage(specifier))
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
if (replacements.length === 0) return void 0;
|
|
212
|
-
let transformed = code;
|
|
213
|
-
for (const r of replacements.toSorted((a, b) => b.start - a.start)) transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);
|
|
214
|
-
return {
|
|
215
|
-
code: transformed,
|
|
216
|
-
map: null
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
const ENVIRONMENT_NAME = "tailor-runtime";
|
|
222
|
-
/**
|
|
223
|
-
* Vite plugin that resolves the tailor-runtime environment and injects setup files.
|
|
224
|
-
*
|
|
225
|
-
* Vitest resolves environments starting with "." or "/" as file paths.
|
|
226
|
-
* This plugin rewrites `environment: "tailor-runtime"` to the absolute path
|
|
227
|
-
* of the bundled environment module, both at the top-level and per-project.
|
|
228
|
-
* It also injects the setup file that removes Vitest-dependent globals
|
|
229
|
-
* (like `performance`) per-test via beforeEach/afterEach hooks.
|
|
230
|
-
* @param options - Optional configuration
|
|
231
|
-
* @param options.config - Path to tailor.config.ts to load SecretManager values into mock
|
|
232
|
-
* @returns Vite plugin
|
|
233
|
-
*/
|
|
234
|
-
function createEnvironmentPlugin(options) {
|
|
235
|
-
const currentDir = dirname(fileURLToPath(import.meta.url));
|
|
236
|
-
const environmentPath = resolve(currentDir, "environment.mjs");
|
|
237
|
-
const setupPath = resolve(currentDir, "setup.mjs");
|
|
238
|
-
return {
|
|
239
|
-
name: "tailor-runtime-environment",
|
|
240
|
-
config(config) {
|
|
241
|
-
const testConfig = config.test;
|
|
242
|
-
let usesTailorRuntime = false;
|
|
243
|
-
if (testConfig?.environment === ENVIRONMENT_NAME) {
|
|
244
|
-
testConfig.environment = environmentPath;
|
|
245
|
-
usesTailorRuntime = true;
|
|
246
|
-
}
|
|
247
|
-
if (testConfig?.projects) for (const project of testConfig.projects) {
|
|
248
|
-
const projectTest = project.test;
|
|
249
|
-
if (projectTest?.environment === ENVIRONMENT_NAME) {
|
|
250
|
-
projectTest.environment = environmentPath;
|
|
251
|
-
usesTailorRuntime = true;
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
delete process.env.__TAILOR_RUNTIME_CONFIG;
|
|
255
|
-
if (options?.config && usesTailorRuntime) {
|
|
256
|
-
const configAbsPath = resolve(config.root ?? process.cwd(), options.config);
|
|
257
|
-
process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;
|
|
258
|
-
}
|
|
259
|
-
if (testConfig && typeof testConfig.setupFiles === "string") testConfig.setupFiles = [testConfig.setupFiles];
|
|
260
|
-
return { test: { setupFiles: [setupPath] } };
|
|
261
|
-
}
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
//#endregion
|
|
266
|
-
//#region src/vitest/mocks/aigateway.ts
|
|
267
|
-
/**
|
|
268
|
-
* Acquire a disposable mock for `tailor.aigateway`. Restored on dispose.
|
|
269
|
-
* @param options - Initial AI Gateway URL fixtures
|
|
270
|
-
* @returns Disposable AI Gateway mock control object
|
|
271
|
-
* @example
|
|
272
|
-
* ```typescript
|
|
273
|
-
* import { mockAigateway } from "@tailor-platform/sdk/vitest";
|
|
274
|
-
*
|
|
275
|
-
* test("resolves an AI Gateway URL", async () => {
|
|
276
|
-
* using aigateway = mockAigateway({
|
|
277
|
-
* urls: { "my-aigateway": "https://my-aigateway.example.com" },
|
|
278
|
-
* });
|
|
279
|
-
* aigateway.setUrl("my-aigateway", "https://replacement.example.com");
|
|
280
|
-
* // …
|
|
281
|
-
* });
|
|
282
|
-
* ```
|
|
283
|
-
*/
|
|
284
|
-
function mockAigateway(options = {}) {
|
|
285
|
-
const root = tailorRoot();
|
|
286
|
-
const prev = root.aigateway;
|
|
287
|
-
let urls = { ...options.urls };
|
|
288
|
-
async function defaultGet(name) {
|
|
289
|
-
const url = urls[name];
|
|
290
|
-
if (url === void 0) throw new Error(`No AI Gateway registered for "${name}". Acquire mockAigateway() and call setUrls(...).`);
|
|
291
|
-
return { url };
|
|
292
|
-
}
|
|
293
|
-
const get = vi.fn(defaultGet);
|
|
294
|
-
root.aigateway = { get };
|
|
295
|
-
return withDispose({
|
|
296
|
-
/** The `get` `vi.fn`. */
|
|
297
|
-
get,
|
|
298
|
-
setUrls(value) {
|
|
299
|
-
urls = value;
|
|
300
|
-
},
|
|
301
|
-
setUrl(name, url) {
|
|
302
|
-
urls = {
|
|
303
|
-
...urls,
|
|
304
|
-
[name]: url
|
|
305
|
-
};
|
|
306
|
-
},
|
|
307
|
-
get calls() {
|
|
308
|
-
return get.mock.calls.map(([name]) => ({ name }));
|
|
309
|
-
},
|
|
310
|
-
clear() {
|
|
311
|
-
get.mockClear();
|
|
312
|
-
},
|
|
313
|
-
reset() {
|
|
314
|
-
urls = {};
|
|
315
|
-
get.mockReset();
|
|
316
|
-
get.mockImplementation(defaultGet);
|
|
317
|
-
}
|
|
318
|
-
}, () => {
|
|
319
|
-
root.aigateway = prev;
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
//#endregion
|
|
324
|
-
//#region src/vitest/mocks/authconnection.ts
|
|
325
|
-
/**
|
|
326
|
-
* Acquire a disposable mock for `tailor.authconnection`. Restored on dispose.
|
|
327
|
-
* @param options - Initial token fixtures and fallback behavior
|
|
328
|
-
* @returns Disposable AuthConnection mock control object
|
|
329
|
-
* @example
|
|
330
|
-
* ```typescript
|
|
331
|
-
* import { mockAuthconnection } from "@tailor-platform/sdk/vitest";
|
|
332
|
-
*
|
|
333
|
-
* test("returns configured token", async () => {
|
|
334
|
-
* using ac = mockAuthconnection({ tokens: { google: { access_token: "ya29.xxx" } } });
|
|
335
|
-
* ac.setToken("google", { access_token: "replacement" });
|
|
336
|
-
* // …
|
|
337
|
-
* });
|
|
338
|
-
* ```
|
|
339
|
-
*/
|
|
340
|
-
function mockAuthconnection(options = {}) {
|
|
341
|
-
const root = tailorRoot();
|
|
342
|
-
const prev = root.authconnection;
|
|
343
|
-
let tokens = { ...options.tokens };
|
|
344
|
-
async function defaultGetConnectionToken(connectionName) {
|
|
345
|
-
const token = tokens[connectionName];
|
|
346
|
-
if (token) return token;
|
|
347
|
-
if (options.onUnhandled === "error") throw new Error(`No AuthConnection token configured for "${connectionName}"`);
|
|
348
|
-
return { access_token: "mock-token" };
|
|
349
|
-
}
|
|
350
|
-
const getConnectionToken = vi.fn(defaultGetConnectionToken);
|
|
351
|
-
root.authconnection = { getConnectionToken };
|
|
352
|
-
return withDispose({
|
|
353
|
-
/** The `getConnectionToken` `vi.fn`. */
|
|
354
|
-
getConnectionToken,
|
|
355
|
-
setTokens(value) {
|
|
356
|
-
tokens = value;
|
|
357
|
-
},
|
|
358
|
-
setToken(connectionName, token) {
|
|
359
|
-
tokens = {
|
|
360
|
-
...tokens,
|
|
361
|
-
[connectionName]: token
|
|
362
|
-
};
|
|
363
|
-
},
|
|
364
|
-
get calls() {
|
|
365
|
-
return getConnectionToken.mock.calls.map(([connectionName]) => ({ connectionName }));
|
|
366
|
-
},
|
|
367
|
-
clear() {
|
|
368
|
-
getConnectionToken.mockClear();
|
|
369
|
-
},
|
|
370
|
-
reset() {
|
|
371
|
-
tokens = {};
|
|
372
|
-
getConnectionToken.mockReset();
|
|
373
|
-
getConnectionToken.mockImplementation(defaultGetConnectionToken);
|
|
374
|
-
}
|
|
375
|
-
}, () => {
|
|
376
|
-
root.authconnection = prev;
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
//#endregion
|
|
381
|
-
//#region src/vitest/mocks/file.ts
|
|
382
|
-
const FILE_METHODS = [
|
|
383
|
-
"upload",
|
|
384
|
-
"download",
|
|
385
|
-
"downloadAsBase64",
|
|
386
|
-
"delete",
|
|
387
|
-
"getMetadata",
|
|
388
|
-
"downloadStream",
|
|
389
|
-
"uploadStream"
|
|
390
|
-
];
|
|
391
|
-
const FILE_DEFAULTS = {
|
|
392
|
-
upload: { metadata: {
|
|
393
|
-
fileSize: 0,
|
|
394
|
-
sha256sum: ""
|
|
395
|
-
} },
|
|
396
|
-
download: {
|
|
397
|
-
data: /* @__PURE__ */ new Uint8Array(),
|
|
398
|
-
metadata: {
|
|
399
|
-
contentType: "",
|
|
400
|
-
fileSize: 0,
|
|
401
|
-
sha256sum: "",
|
|
402
|
-
lastUploadedAt: ""
|
|
403
|
-
}
|
|
404
|
-
},
|
|
405
|
-
downloadAsBase64: {
|
|
406
|
-
data: "",
|
|
407
|
-
metadata: {
|
|
408
|
-
contentType: "",
|
|
409
|
-
fileSize: 0,
|
|
410
|
-
sha256sum: "",
|
|
411
|
-
lastUploadedAt: ""
|
|
412
|
-
}
|
|
413
|
-
},
|
|
414
|
-
getMetadata: {
|
|
415
|
-
contentType: "",
|
|
416
|
-
fileSize: 0,
|
|
417
|
-
sha256sum: "",
|
|
418
|
-
urlPath: ""
|
|
419
|
-
},
|
|
420
|
-
downloadStream: null,
|
|
421
|
-
uploadStream: { metadata: {
|
|
422
|
-
fileSize: 0,
|
|
423
|
-
sha256sum: ""
|
|
424
|
-
} }
|
|
425
|
-
};
|
|
426
|
-
/**
|
|
427
|
-
* Acquire a disposable mock for `tailordb.file`. Restored on dispose.
|
|
428
|
-
* @param options - Controls behavior for calls without a configured result
|
|
429
|
-
* @returns Disposable File mock control object
|
|
430
|
-
* @example
|
|
431
|
-
* ```typescript
|
|
432
|
-
* import { mockFile } from "@tailor-platform/sdk/vitest";
|
|
433
|
-
*
|
|
434
|
-
* test("mock file download", async () => {
|
|
435
|
-
* using file = mockFile();
|
|
436
|
-
* file.download.mockResolvedValue({ data: new Uint8Array(), metadata: { ... } });
|
|
437
|
-
* // …
|
|
438
|
-
* });
|
|
439
|
-
* ```
|
|
440
|
-
*/
|
|
441
|
-
function mockFile(options = {}) {
|
|
442
|
-
const root = tailordbRoot();
|
|
443
|
-
const prev = root.file;
|
|
444
|
-
const { onUnhandled = "fallback" } = options;
|
|
445
|
-
const queue = [];
|
|
446
|
-
const calls = [];
|
|
447
|
-
let resolver = () => null;
|
|
448
|
-
function handle(method, namespace, typeName, fieldName, recordId) {
|
|
449
|
-
if (queue.length > 0) return queue.shift();
|
|
450
|
-
const resolved = resolver(method, {
|
|
451
|
-
method,
|
|
452
|
-
namespace,
|
|
453
|
-
typeName,
|
|
454
|
-
fieldName,
|
|
455
|
-
recordId
|
|
456
|
-
});
|
|
457
|
-
if (resolved != null) return resolved;
|
|
458
|
-
if (onUnhandled === "error") throw new Error(`No File mock configured for "${method}"`);
|
|
459
|
-
const fallback = FILE_DEFAULTS[method];
|
|
460
|
-
return fallback === void 0 ? void 0 : structuredClone(fallback);
|
|
461
|
-
}
|
|
462
|
-
const upload = vi.fn(async (...args) => {
|
|
463
|
-
const [namespace, typeName, fieldName, recordId] = args;
|
|
464
|
-
return handle("upload", namespace, typeName, fieldName, recordId);
|
|
465
|
-
});
|
|
466
|
-
const download = vi.fn(async (...args) => handle("download", ...args));
|
|
467
|
-
const downloadAsBase64 = vi.fn(async (...args) => handle("downloadAsBase64", ...args));
|
|
468
|
-
const deleteFile = vi.fn(async (...args) => {
|
|
469
|
-
handle("delete", ...args);
|
|
470
|
-
});
|
|
471
|
-
const getMetadata = vi.fn(async (...args) => handle("getMetadata", ...args));
|
|
472
|
-
const downloadStream = vi.fn(async (...args) => {
|
|
473
|
-
const resolved = handle("downloadStream", ...args);
|
|
474
|
-
if (resolved != null) return resolved;
|
|
475
|
-
return {
|
|
476
|
-
body: new ReadableStream({ start(controller) {
|
|
477
|
-
controller.close();
|
|
478
|
-
} }),
|
|
479
|
-
metadata: {
|
|
480
|
-
contentType: "",
|
|
481
|
-
fileSize: 0,
|
|
482
|
-
sha256sum: "",
|
|
483
|
-
lastUploadedAt: ""
|
|
484
|
-
}
|
|
485
|
-
};
|
|
486
|
-
});
|
|
487
|
-
const uploadStream = vi.fn(async (...args) => {
|
|
488
|
-
const [namespace, typeName, fieldName, recordId] = args;
|
|
489
|
-
return handle("uploadStream", namespace, typeName, fieldName, recordId);
|
|
490
|
-
});
|
|
491
|
-
const mocks = {
|
|
492
|
-
upload,
|
|
493
|
-
download,
|
|
494
|
-
downloadAsBase64,
|
|
495
|
-
delete: deleteFile,
|
|
496
|
-
getMetadata,
|
|
497
|
-
downloadStream,
|
|
498
|
-
uploadStream
|
|
499
|
-
};
|
|
500
|
-
function track(method, operation) {
|
|
501
|
-
return function(...args) {
|
|
502
|
-
calls.push({
|
|
503
|
-
method,
|
|
504
|
-
namespace: args[0],
|
|
505
|
-
typeName: args[1],
|
|
506
|
-
fieldName: args[2],
|
|
507
|
-
recordId: args[3]
|
|
508
|
-
});
|
|
509
|
-
return operation.apply(this, args);
|
|
510
|
-
};
|
|
511
|
-
}
|
|
512
|
-
root.file = {
|
|
513
|
-
upload: track("upload", upload),
|
|
514
|
-
download: track("download", download),
|
|
515
|
-
downloadAsBase64: track("downloadAsBase64", downloadAsBase64),
|
|
516
|
-
delete: track("delete", deleteFile),
|
|
517
|
-
getMetadata: track("getMetadata", getMetadata),
|
|
518
|
-
downloadStream: track("downloadStream", downloadStream),
|
|
519
|
-
uploadStream: track("uploadStream", uploadStream)
|
|
520
|
-
};
|
|
521
|
-
function allMocks() {
|
|
522
|
-
return FILE_METHODS.map((method) => mocks[method]);
|
|
523
|
-
}
|
|
524
|
-
return withDispose({
|
|
525
|
-
...mocks,
|
|
526
|
-
setResolver(value) {
|
|
527
|
-
resolver = value;
|
|
528
|
-
},
|
|
529
|
-
/**
|
|
530
|
-
* Enqueue a single result for the next `tailordb.file` call.
|
|
531
|
-
* The queue is shared across all methods and namespaces.
|
|
532
|
-
* @param result - Result to return from the next file call
|
|
533
|
-
*/
|
|
534
|
-
enqueueResult(result) {
|
|
535
|
-
queue.push(result);
|
|
536
|
-
},
|
|
537
|
-
/**
|
|
538
|
-
* Enqueue results for multiple subsequent `tailordb.file` calls.
|
|
539
|
-
* The queue is shared across all methods and namespaces.
|
|
540
|
-
* @param results - Results to enqueue, one per upcoming call
|
|
541
|
-
*/
|
|
542
|
-
enqueueResults(...results) {
|
|
543
|
-
queue.push(...results);
|
|
544
|
-
},
|
|
545
|
-
get calls() {
|
|
546
|
-
return calls;
|
|
547
|
-
},
|
|
548
|
-
clear() {
|
|
549
|
-
calls.length = 0;
|
|
550
|
-
for (const mock of allMocks()) mock.mockClear();
|
|
551
|
-
},
|
|
552
|
-
reset() {
|
|
553
|
-
queue.length = 0;
|
|
554
|
-
calls.length = 0;
|
|
555
|
-
resolver = () => null;
|
|
556
|
-
for (const mock of allMocks()) mock.mockReset();
|
|
557
|
-
}
|
|
558
|
-
}, () => {
|
|
559
|
-
root.file = prev;
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
//#endregion
|
|
564
|
-
//#region src/vitest/mocks/iconv.ts
|
|
565
|
-
function isUtf8(encoding) {
|
|
566
|
-
return encoding === "UTF8" || encoding === "UTF-8";
|
|
567
|
-
}
|
|
568
|
-
function defaultIconvResult(method, args) {
|
|
569
|
-
switch (method) {
|
|
570
|
-
case "convert":
|
|
571
|
-
case "convertBuffer": return isUtf8(args[2]) ? "" : /* @__PURE__ */ new Uint8Array();
|
|
572
|
-
case "decode": return "";
|
|
573
|
-
case "encode": return isUtf8(args[1]) ? "" : /* @__PURE__ */ new Uint8Array();
|
|
574
|
-
case "encodings": return [];
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Acquire a disposable mock for `tailor.iconv`. Restored on dispose.
|
|
579
|
-
* @param options - Fallback behavior for unconfigured operations
|
|
580
|
-
* @returns Disposable Iconv mock control object
|
|
581
|
-
* @example
|
|
582
|
-
* ```typescript
|
|
583
|
-
* import { mockIconv } from "@tailor-platform/sdk/vitest";
|
|
584
|
-
*
|
|
585
|
-
* test("mock encoding conversion", () => {
|
|
586
|
-
* using iconv = mockIconv();
|
|
587
|
-
* iconv.decode.mockReturnValue("decoded-text");
|
|
588
|
-
* // …
|
|
589
|
-
* });
|
|
590
|
-
* ```
|
|
591
|
-
*/
|
|
592
|
-
function mockIconv(options = {}) {
|
|
593
|
-
const root = tailorRoot();
|
|
594
|
-
const prev = root.iconv;
|
|
595
|
-
let resolver = null;
|
|
596
|
-
const calls = [];
|
|
597
|
-
function resolve(method, args) {
|
|
598
|
-
if (resolver) {
|
|
599
|
-
const result = resolver(method, args);
|
|
600
|
-
if (result != null) return result;
|
|
601
|
-
}
|
|
602
|
-
if (options.onUnhandled === "error") throw new Error(`No Iconv mock behavior configured for "${method}"`);
|
|
603
|
-
return defaultIconvResult(method, args);
|
|
604
|
-
}
|
|
605
|
-
function defaultConvert(input, fromEncoding, toEncoding) {
|
|
606
|
-
return resolve("convert", [
|
|
607
|
-
input,
|
|
608
|
-
fromEncoding,
|
|
609
|
-
toEncoding
|
|
610
|
-
]);
|
|
611
|
-
}
|
|
612
|
-
function defaultConvertBuffer(input, fromEncoding, toEncoding) {
|
|
613
|
-
return resolve("convertBuffer", [
|
|
614
|
-
input,
|
|
615
|
-
fromEncoding,
|
|
616
|
-
toEncoding
|
|
617
|
-
]);
|
|
618
|
-
}
|
|
619
|
-
function defaultDecode(input, encoding) {
|
|
620
|
-
return resolve("decode", [input, encoding]);
|
|
621
|
-
}
|
|
622
|
-
function defaultEncode(input, encoding) {
|
|
623
|
-
return resolve("encode", [input, encoding]);
|
|
624
|
-
}
|
|
625
|
-
function defaultEncodings() {
|
|
626
|
-
return resolve("encodings", []);
|
|
627
|
-
}
|
|
628
|
-
const convert = vi.fn(defaultConvert);
|
|
629
|
-
const convertBuffer = vi.fn(defaultConvertBuffer);
|
|
630
|
-
const decode = vi.fn(defaultDecode);
|
|
631
|
-
const encode = vi.fn(defaultEncode);
|
|
632
|
-
const encodings = vi.fn(defaultEncodings);
|
|
633
|
-
function track(method, operation) {
|
|
634
|
-
return function(...args) {
|
|
635
|
-
calls.push({
|
|
636
|
-
method,
|
|
637
|
-
args: [...args]
|
|
638
|
-
});
|
|
639
|
-
return operation.apply(this, args);
|
|
640
|
-
};
|
|
641
|
-
}
|
|
642
|
-
const trackedConvert = track("convert", convert);
|
|
643
|
-
const trackedConvertBuffer = track("convertBuffer", convertBuffer);
|
|
644
|
-
const trackedDecode = track("decode", decode);
|
|
645
|
-
const trackedEncode = track("encode", encode);
|
|
646
|
-
const trackedEncodings = track("encodings", encodings);
|
|
647
|
-
class MockIconv {
|
|
648
|
-
#fromEncoding;
|
|
649
|
-
#toEncoding;
|
|
650
|
-
constructor(fromEncoding, toEncoding) {
|
|
651
|
-
this.#fromEncoding = fromEncoding;
|
|
652
|
-
this.#toEncoding = toEncoding;
|
|
653
|
-
}
|
|
654
|
-
convert(input) {
|
|
655
|
-
return trackedConvert.call(this, input, this.#fromEncoding, this.#toEncoding);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
root.iconv = {
|
|
659
|
-
convert: trackedConvert,
|
|
660
|
-
convertBuffer: trackedConvertBuffer,
|
|
661
|
-
decode: trackedDecode,
|
|
662
|
-
encode: trackedEncode,
|
|
663
|
-
encodings: trackedEncodings,
|
|
664
|
-
Iconv: MockIconv
|
|
665
|
-
};
|
|
666
|
-
function clear() {
|
|
667
|
-
calls.length = 0;
|
|
668
|
-
convert.mockClear();
|
|
669
|
-
convertBuffer.mockClear();
|
|
670
|
-
decode.mockClear();
|
|
671
|
-
encode.mockClear();
|
|
672
|
-
encodings.mockClear();
|
|
673
|
-
}
|
|
674
|
-
return withDispose({
|
|
675
|
-
/** The `convert` `vi.fn`. */
|
|
676
|
-
convert,
|
|
677
|
-
/** The `convertBuffer` `vi.fn`. */
|
|
678
|
-
convertBuffer,
|
|
679
|
-
/** The `decode` `vi.fn`. */
|
|
680
|
-
decode,
|
|
681
|
-
/** The `encode` `vi.fn`. */
|
|
682
|
-
encode,
|
|
683
|
-
/** The `encodings` `vi.fn`. */
|
|
684
|
-
encodings,
|
|
685
|
-
setResolver(value) {
|
|
686
|
-
resolver = value;
|
|
687
|
-
},
|
|
688
|
-
get calls() {
|
|
689
|
-
return calls;
|
|
690
|
-
},
|
|
691
|
-
clear,
|
|
692
|
-
reset() {
|
|
693
|
-
resolver = null;
|
|
694
|
-
calls.length = 0;
|
|
695
|
-
convert.mockReset();
|
|
696
|
-
convert.mockImplementation(defaultConvert);
|
|
697
|
-
convertBuffer.mockReset();
|
|
698
|
-
convertBuffer.mockImplementation(defaultConvertBuffer);
|
|
699
|
-
decode.mockReset();
|
|
700
|
-
decode.mockImplementation(defaultDecode);
|
|
701
|
-
encode.mockReset();
|
|
702
|
-
encode.mockImplementation(defaultEncode);
|
|
703
|
-
encodings.mockReset();
|
|
704
|
-
encodings.mockImplementation(defaultEncodings);
|
|
705
|
-
}
|
|
706
|
-
}, () => {
|
|
707
|
-
root.iconv = prev;
|
|
708
|
-
});
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
//#endregion
|
|
712
|
-
//#region src/vitest/mocks/idp.ts
|
|
713
|
-
const IDP_METHODS = [
|
|
714
|
-
"users",
|
|
715
|
-
"user",
|
|
716
|
-
"userByName",
|
|
717
|
-
"createUser",
|
|
718
|
-
"updateUser",
|
|
719
|
-
"deleteUser",
|
|
720
|
-
"sendPasswordResetEmail",
|
|
721
|
-
"unenrollMfa"
|
|
722
|
-
];
|
|
723
|
-
const IDP_USER_DEFAULT = {
|
|
724
|
-
id: "mock-id",
|
|
725
|
-
name: "mock-user",
|
|
726
|
-
disabled: false,
|
|
727
|
-
mfaEnrolled: false,
|
|
728
|
-
mfaFactorIds: []
|
|
729
|
-
};
|
|
730
|
-
const IDP_DEFAULTS = {
|
|
731
|
-
users: {
|
|
732
|
-
users: [],
|
|
733
|
-
nextPageToken: null,
|
|
734
|
-
totalCount: 0
|
|
735
|
-
},
|
|
736
|
-
user: IDP_USER_DEFAULT,
|
|
737
|
-
userByName: IDP_USER_DEFAULT,
|
|
738
|
-
createUser: IDP_USER_DEFAULT,
|
|
739
|
-
updateUser: IDP_USER_DEFAULT,
|
|
740
|
-
deleteUser: true,
|
|
741
|
-
sendPasswordResetEmail: true,
|
|
742
|
-
unenrollMfa: true
|
|
743
|
-
};
|
|
744
|
-
/**
|
|
745
|
-
* Acquire a disposable mock for `tailor.idp`. Restored on dispose.
|
|
746
|
-
* @param options - Controls behavior for calls without a configured result
|
|
747
|
-
* @returns Disposable IDP mock control object
|
|
748
|
-
* @example
|
|
749
|
-
* ```typescript
|
|
750
|
-
* import { mockIdp } from "@tailor-platform/sdk/vitest";
|
|
751
|
-
*
|
|
752
|
-
* test("returns a user", async () => {
|
|
753
|
-
* using idp = mockIdp();
|
|
754
|
-
* idp.namespace("my-idp").user.mockResolvedValue({
|
|
755
|
-
* id: "u-1",
|
|
756
|
-
* name: "alice",
|
|
757
|
-
* disabled: false,
|
|
758
|
-
* mfaEnrolled: false,
|
|
759
|
-
* mfaFactorIds: [],
|
|
760
|
-
* });
|
|
761
|
-
* // …
|
|
762
|
-
* });
|
|
763
|
-
* ```
|
|
764
|
-
*/
|
|
765
|
-
function mockIdp(options = {}) {
|
|
766
|
-
const root = tailorRoot();
|
|
767
|
-
const prev = root.idp;
|
|
768
|
-
const { onUnhandled = "fallback" } = options;
|
|
769
|
-
const queue = [];
|
|
770
|
-
const calls = [];
|
|
771
|
-
let resolver = () => null;
|
|
772
|
-
const namespaces = /* @__PURE__ */ new Map();
|
|
773
|
-
function compatibilityArgs(method, args) {
|
|
774
|
-
return method === "users" && args.length === 0 ? [void 0] : args;
|
|
775
|
-
}
|
|
776
|
-
function handle(method, args, namespace) {
|
|
777
|
-
if (queue.length > 0) return queue.shift();
|
|
778
|
-
const resolved = resolver(method, compatibilityArgs(method, args), namespace);
|
|
779
|
-
if (resolved != null) return resolved;
|
|
780
|
-
if (onUnhandled === "error") throw new Error(`No IdP mock configured for "${namespace}.${method}"`);
|
|
781
|
-
return structuredClone(IDP_DEFAULTS[method]);
|
|
782
|
-
}
|
|
783
|
-
function createNamespaceMocks(namespace) {
|
|
784
|
-
return {
|
|
785
|
-
users: vi.fn(async (...args) => handle("users", args, namespace)),
|
|
786
|
-
user: vi.fn(async (...args) => handle("user", args, namespace)),
|
|
787
|
-
userByName: vi.fn(async (...args) => handle("userByName", args, namespace)),
|
|
788
|
-
createUser: vi.fn(async (...args) => handle("createUser", args, namespace)),
|
|
789
|
-
updateUser: vi.fn(async (...args) => handle("updateUser", args, namespace)),
|
|
790
|
-
deleteUser: vi.fn(async (...args) => handle("deleteUser", args, namespace)),
|
|
791
|
-
sendPasswordResetEmail: vi.fn(async (...args) => handle("sendPasswordResetEmail", args, namespace)),
|
|
792
|
-
unenrollMfa: vi.fn(async (...args) => handle("unenrollMfa", args, namespace))
|
|
793
|
-
};
|
|
794
|
-
}
|
|
795
|
-
function namespace(name) {
|
|
796
|
-
const existing = namespaces.get(name);
|
|
797
|
-
if (existing) return existing;
|
|
798
|
-
const mocks = createNamespaceMocks(name);
|
|
799
|
-
namespaces.set(name, mocks);
|
|
800
|
-
return mocks;
|
|
801
|
-
}
|
|
802
|
-
function track(method, mock, namespaceName) {
|
|
803
|
-
return function(...args) {
|
|
804
|
-
calls.push({
|
|
805
|
-
method,
|
|
806
|
-
args: [...compatibilityArgs(method, args)],
|
|
807
|
-
namespace: namespaceName
|
|
808
|
-
});
|
|
809
|
-
return mock.apply(this, args);
|
|
810
|
-
};
|
|
811
|
-
}
|
|
812
|
-
const defaultClient = function(config) {
|
|
813
|
-
const mocks = namespace(config.namespace);
|
|
814
|
-
this.users = track("users", mocks.users, config.namespace);
|
|
815
|
-
this.user = track("user", mocks.user, config.namespace);
|
|
816
|
-
this.userByName = track("userByName", mocks.userByName, config.namespace);
|
|
817
|
-
this.createUser = track("createUser", mocks.createUser, config.namespace);
|
|
818
|
-
this.updateUser = track("updateUser", mocks.updateUser, config.namespace);
|
|
819
|
-
this.deleteUser = track("deleteUser", mocks.deleteUser, config.namespace);
|
|
820
|
-
this.sendPasswordResetEmail = track("sendPasswordResetEmail", mocks.sendPasswordResetEmail, config.namespace);
|
|
821
|
-
this.unenrollMfa = track("unenrollMfa", mocks.unenrollMfa, config.namespace);
|
|
822
|
-
};
|
|
823
|
-
const Client = vi.fn(defaultClient);
|
|
824
|
-
root.idp = { Client };
|
|
825
|
-
function allMocks() {
|
|
826
|
-
return [...namespaces.values()].flatMap((mocks) => IDP_METHODS.map((method) => mocks[method]));
|
|
827
|
-
}
|
|
828
|
-
return withDispose({
|
|
829
|
-
/** The mock IDP `Client` constructor (`vi.fn`). */
|
|
830
|
-
Client,
|
|
831
|
-
namespace,
|
|
832
|
-
setResolver(value) {
|
|
833
|
-
resolver = value;
|
|
834
|
-
},
|
|
835
|
-
/**
|
|
836
|
-
* Enqueue a single result for the next IDP call.
|
|
837
|
-
* The queue is shared across all methods and namespaces.
|
|
838
|
-
* @param result - Result to return from the next IDP call
|
|
839
|
-
*/
|
|
840
|
-
enqueueResult(result) {
|
|
841
|
-
queue.push(result);
|
|
842
|
-
},
|
|
843
|
-
/**
|
|
844
|
-
* Enqueue results for multiple subsequent IDP calls.
|
|
845
|
-
* The queue is shared across all methods and namespaces.
|
|
846
|
-
* @param results - Results to enqueue, one per upcoming call
|
|
847
|
-
*/
|
|
848
|
-
enqueueResults(...results) {
|
|
849
|
-
queue.push(...results);
|
|
850
|
-
},
|
|
851
|
-
get calls() {
|
|
852
|
-
return calls;
|
|
853
|
-
},
|
|
854
|
-
clear() {
|
|
855
|
-
calls.length = 0;
|
|
856
|
-
Client.mockClear();
|
|
857
|
-
for (const mock of allMocks()) mock.mockClear();
|
|
858
|
-
},
|
|
859
|
-
reset() {
|
|
860
|
-
queue.length = 0;
|
|
861
|
-
calls.length = 0;
|
|
862
|
-
resolver = () => null;
|
|
863
|
-
Client.mockReset();
|
|
864
|
-
Client.mockImplementation(defaultClient);
|
|
865
|
-
for (const mock of allMocks()) mock.mockReset();
|
|
866
|
-
}
|
|
867
|
-
}, () => {
|
|
868
|
-
root.idp = prev;
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
//#endregion
|
|
873
|
-
//#region src/vitest/mocks/logger.ts
|
|
874
|
-
/**
|
|
875
|
-
* Acquire a disposable mock for `tailor.logger`. Each method is a `vi.fn`, so
|
|
876
|
-
* calls can be asserted directly; `calls` returns the `debug`/`info`/`warn`/
|
|
877
|
-
* `error` entries in the order they were emitted. Restored on dispose.
|
|
878
|
-
* @param _options - Reserved for future initial fixtures
|
|
879
|
-
* @returns Disposable logger mock control object
|
|
880
|
-
* @example
|
|
881
|
-
* ```typescript
|
|
882
|
-
* import { mockLogger } from "@tailor-platform/sdk/vitest";
|
|
883
|
-
*
|
|
884
|
-
* test("logs the processed order", () => {
|
|
885
|
-
* using logger = mockLogger();
|
|
886
|
-
* // …run code that calls tailor.logger.info…
|
|
887
|
-
* expect(logger.info).toHaveBeenCalledWith("order processed", { orderId: "o-1" });
|
|
888
|
-
* });
|
|
889
|
-
* ```
|
|
890
|
-
*/
|
|
891
|
-
function mockLogger(_options = {}) {
|
|
892
|
-
const root = tailorRoot();
|
|
893
|
-
const prev = root.logger;
|
|
894
|
-
const debug = vi.fn((_message, _attributes) => {});
|
|
895
|
-
const info = vi.fn((_message, _attributes) => {});
|
|
896
|
-
const warn = vi.fn((_message, _attributes) => {});
|
|
897
|
-
const error = vi.fn((_message, _attributes) => {});
|
|
898
|
-
const setAttributes = vi.fn((_attributes) => {});
|
|
899
|
-
root.logger = {
|
|
900
|
-
debug,
|
|
901
|
-
info,
|
|
902
|
-
warn,
|
|
903
|
-
error,
|
|
904
|
-
setAttributes
|
|
905
|
-
};
|
|
906
|
-
const severityFns = {
|
|
907
|
-
debug,
|
|
908
|
-
info,
|
|
909
|
-
warn,
|
|
910
|
-
error
|
|
911
|
-
};
|
|
912
|
-
return withDispose({
|
|
913
|
-
/** The `debug` `vi.fn`. */
|
|
914
|
-
debug,
|
|
915
|
-
/** The `info` `vi.fn`. */
|
|
916
|
-
info,
|
|
917
|
-
/** The `warn` `vi.fn`. */
|
|
918
|
-
warn,
|
|
919
|
-
/** The `error` `vi.fn`. */
|
|
920
|
-
error,
|
|
921
|
-
/** The `setAttributes` `vi.fn`. */
|
|
922
|
-
setAttributes,
|
|
923
|
-
get calls() {
|
|
924
|
-
return Object.entries(severityFns).flatMap(([severity, fn]) => fn.mock.calls.map((args, i) => ({
|
|
925
|
-
order: fn.mock.invocationCallOrder[i] ?? 0,
|
|
926
|
-
call: {
|
|
927
|
-
severity,
|
|
928
|
-
message: args[0],
|
|
929
|
-
attributes: args[1]
|
|
930
|
-
}
|
|
931
|
-
}))).toSorted((a, b) => a.order - b.order).map((e) => e.call);
|
|
932
|
-
},
|
|
933
|
-
clear() {
|
|
934
|
-
debug.mockClear();
|
|
935
|
-
info.mockClear();
|
|
936
|
-
warn.mockClear();
|
|
937
|
-
error.mockClear();
|
|
938
|
-
setAttributes.mockClear();
|
|
939
|
-
},
|
|
940
|
-
reset() {
|
|
941
|
-
debug.mockReset();
|
|
942
|
-
info.mockReset();
|
|
943
|
-
warn.mockReset();
|
|
944
|
-
error.mockReset();
|
|
945
|
-
setAttributes.mockReset();
|
|
946
|
-
}
|
|
947
|
-
}, () => {
|
|
948
|
-
root.logger = prev;
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
//#endregion
|
|
953
|
-
//#region src/vitest/mocks/tailordb.ts
|
|
954
|
-
function testRegex(regex, value) {
|
|
955
|
-
const lastIndex = regex.lastIndex;
|
|
956
|
-
regex.lastIndex = 0;
|
|
957
|
-
try {
|
|
958
|
-
return regex.test(value);
|
|
959
|
-
} finally {
|
|
960
|
-
regex.lastIndex = lastIndex;
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
var MockQueryResult = class {
|
|
964
|
-
command;
|
|
965
|
-
rowCount;
|
|
966
|
-
rows;
|
|
967
|
-
constructor(rows) {
|
|
968
|
-
this.command = "";
|
|
969
|
-
this.rowCount = rows.length;
|
|
970
|
-
this.rows = rows;
|
|
971
|
-
}
|
|
972
|
-
};
|
|
973
|
-
/**
|
|
974
|
-
* Acquire a disposable mock for TailorDB operations. Installs a mock
|
|
975
|
-
* `tailordb.Client` whose `queryObject` is a shared `vi.fn()` (so query
|
|
976
|
-
* responses can be staged before the client is constructed). Restored on
|
|
977
|
-
* dispose.
|
|
978
|
-
* @param options - Query fallback behavior
|
|
979
|
-
* @returns Disposable TailorDB mock control object
|
|
980
|
-
* @example
|
|
981
|
-
* ```typescript
|
|
982
|
-
* import { mockTailordb } from "@tailor-platform/sdk/vitest";
|
|
983
|
-
*
|
|
984
|
-
* test("query-based", async () => {
|
|
985
|
-
* using db = mockTailordb();
|
|
986
|
-
* db.onQuery({ sql: /FROM users/, params: ["u-1"] }).returnsRows([{ age: 30 }]);
|
|
987
|
-
* // …
|
|
988
|
-
* expect(db.queryObject).toHaveBeenCalled();
|
|
989
|
-
* expect(db.Client).toHaveBeenCalledWith({ namespace: "tailordb" });
|
|
990
|
-
* });
|
|
991
|
-
* ```
|
|
992
|
-
*/
|
|
993
|
-
function mockTailordb(options = {}) {
|
|
994
|
-
const root = tailordbRoot();
|
|
995
|
-
const prevClient = root.Client;
|
|
996
|
-
const rules = [];
|
|
997
|
-
let queryResolver;
|
|
998
|
-
function matchesQuery(matcher, query, params) {
|
|
999
|
-
if (typeof matcher === "function") return matcher(query, params);
|
|
1000
|
-
if (typeof matcher === "string") return query === matcher;
|
|
1001
|
-
if (matcher instanceof RegExp) return testRegex(matcher, query);
|
|
1002
|
-
let sqlMatches;
|
|
1003
|
-
if (typeof matcher.sql === "string") sqlMatches = query === matcher.sql;
|
|
1004
|
-
else sqlMatches = testRegex(matcher.sql, query);
|
|
1005
|
-
if (!sqlMatches || matcher.params === void 0) return sqlMatches;
|
|
1006
|
-
if (typeof matcher.params === "function") return matcher.params(params);
|
|
1007
|
-
const expectedParams = matcher.params;
|
|
1008
|
-
return params.length === expectedParams.length && params.every((value, index) => isEqual(value, expectedParams[index]));
|
|
1009
|
-
}
|
|
1010
|
-
function queryResponse(response) {
|
|
1011
|
-
if (response.type === "error") throw response.error;
|
|
1012
|
-
return new MockQueryResult(response.rows);
|
|
1013
|
-
}
|
|
1014
|
-
async function defaultQuery(query, params = []) {
|
|
1015
|
-
for (let i = rules.length - 1; i >= 0; i -= 1) {
|
|
1016
|
-
const rule = rules[i];
|
|
1017
|
-
if (!rule || !matchesQuery(rule.matcher, query, params)) continue;
|
|
1018
|
-
const once = rule.once.shift();
|
|
1019
|
-
if (once) return queryResponse(once);
|
|
1020
|
-
if (rule.fallback) return queryResponse(rule.fallback);
|
|
1021
|
-
}
|
|
1022
|
-
if (queryResolver) return new MockQueryResult(queryResolver(query, params) ?? []);
|
|
1023
|
-
if (options.onUnhandled === "error") throw new Error(`No TailorDB query behavior matched: ${query}`);
|
|
1024
|
-
return new MockQueryResult([]);
|
|
1025
|
-
}
|
|
1026
|
-
const queryObject = vi.fn(defaultQuery);
|
|
1027
|
-
const defaultConnect = async () => {};
|
|
1028
|
-
const connect = vi.fn(defaultConnect);
|
|
1029
|
-
const createdClients = [];
|
|
1030
|
-
function enqueueRowsList(rowsList) {
|
|
1031
|
-
for (const rows of rowsList) queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));
|
|
1032
|
-
}
|
|
1033
|
-
const defaultClient = function(config) {
|
|
1034
|
-
const record = {
|
|
1035
|
-
namespace: config?.namespace,
|
|
1036
|
-
ended: false
|
|
1037
|
-
};
|
|
1038
|
-
createdClients.push(record);
|
|
1039
|
-
this.connect = connect;
|
|
1040
|
-
this.end = vi.fn(async () => {
|
|
1041
|
-
record.ended = true;
|
|
1042
|
-
});
|
|
1043
|
-
this.queryObject = queryObject;
|
|
1044
|
-
this.createTransaction = (name) => {
|
|
1045
|
-
if (!name) throw new Error("Transaction name must be a non-empty string");
|
|
1046
|
-
return {
|
|
1047
|
-
begin: async () => {},
|
|
1048
|
-
commit: async () => {},
|
|
1049
|
-
rollback: async () => {},
|
|
1050
|
-
queryObject
|
|
1051
|
-
};
|
|
1052
|
-
};
|
|
1053
|
-
};
|
|
1054
|
-
const Client = vi.fn(defaultClient);
|
|
1055
|
-
root.Client = Client;
|
|
1056
|
-
return withDispose({
|
|
1057
|
-
/** The mock `tailordb.Client` constructor (`vi.fn`). */
|
|
1058
|
-
Client,
|
|
1059
|
-
/** The shared `queryObject` `vi.fn` used by every client and transaction. */
|
|
1060
|
-
queryObject,
|
|
1061
|
-
/**
|
|
1062
|
-
* Set a fallback query resolver. Called when the enqueue queue is empty.
|
|
1063
|
-
* @param resolver - Function that returns rows for a given query and params
|
|
1064
|
-
*/
|
|
1065
|
-
setQueryResolver(resolver) {
|
|
1066
|
-
queryResolver = resolver;
|
|
1067
|
-
queryObject.mockImplementation(defaultQuery);
|
|
1068
|
-
},
|
|
1069
|
-
/**
|
|
1070
|
-
* Configure responses for queries matching SQL text, parameters, or a predicate.
|
|
1071
|
-
* More recently registered matchers take precedence.
|
|
1072
|
-
* Do not combine matchers with a direct `queryObject.mockImplementation()` override.
|
|
1073
|
-
* @param matcher - Query matcher
|
|
1074
|
-
* @returns Chainable query behavior
|
|
1075
|
-
*/
|
|
1076
|
-
onQuery(matcher) {
|
|
1077
|
-
const rule = {
|
|
1078
|
-
matcher,
|
|
1079
|
-
once: []
|
|
1080
|
-
};
|
|
1081
|
-
rules.push(rule);
|
|
1082
|
-
const behavior = {
|
|
1083
|
-
returnsRows(rows) {
|
|
1084
|
-
rule.fallback = {
|
|
1085
|
-
type: "rows",
|
|
1086
|
-
rows
|
|
1087
|
-
};
|
|
1088
|
-
return behavior;
|
|
1089
|
-
},
|
|
1090
|
-
returnsRowsOnce(rows) {
|
|
1091
|
-
rule.once.push({
|
|
1092
|
-
type: "rows",
|
|
1093
|
-
rows
|
|
1094
|
-
});
|
|
1095
|
-
return behavior;
|
|
1096
|
-
},
|
|
1097
|
-
rejects(error) {
|
|
1098
|
-
rule.fallback = {
|
|
1099
|
-
type: "error",
|
|
1100
|
-
error
|
|
1101
|
-
};
|
|
1102
|
-
return behavior;
|
|
1103
|
-
},
|
|
1104
|
-
rejectsOnce(error) {
|
|
1105
|
-
rule.once.push({
|
|
1106
|
-
type: "error",
|
|
1107
|
-
error
|
|
1108
|
-
});
|
|
1109
|
-
return behavior;
|
|
1110
|
-
}
|
|
1111
|
-
};
|
|
1112
|
-
return behavior;
|
|
1113
|
-
},
|
|
1114
|
-
/**
|
|
1115
|
-
* Enqueue rows for the next `queryObject` call (FIFO; takes priority over
|
|
1116
|
-
* `setQueryResolver`). Call with no arguments for an empty result.
|
|
1117
|
-
* @param rows - Row objects to return from the next `queryObject` call
|
|
1118
|
-
*/
|
|
1119
|
-
enqueueResult(...rows) {
|
|
1120
|
-
enqueueRowsList([rows]);
|
|
1121
|
-
},
|
|
1122
|
-
/**
|
|
1123
|
-
* Enqueue rows for multiple subsequent `queryObject` calls (FIFO).
|
|
1124
|
-
* @param rowsList - Rows arrays, one per upcoming query
|
|
1125
|
-
*/
|
|
1126
|
-
enqueueResults(...rowsList) {
|
|
1127
|
-
enqueueRowsList(rowsList);
|
|
1128
|
-
},
|
|
1129
|
-
/**
|
|
1130
|
-
* Enqueue row arrays for subsequent queries whose exact order is under test.
|
|
1131
|
-
* @param rowsList - Rows arrays, one per upcoming query
|
|
1132
|
-
*/
|
|
1133
|
-
enqueueRows(...rowsList) {
|
|
1134
|
-
enqueueRowsList(rowsList);
|
|
1135
|
-
},
|
|
1136
|
-
/**
|
|
1137
|
-
* All queries executed via `queryObject`, in order, derived from the vi.fn
|
|
1138
|
-
* call records.
|
|
1139
|
-
* @returns Executed queries array
|
|
1140
|
-
*/
|
|
1141
|
-
get executedQueries() {
|
|
1142
|
-
return queryObject.mock.calls.map(([query, params]) => ({
|
|
1143
|
-
query,
|
|
1144
|
-
params: params ?? []
|
|
1145
|
-
}));
|
|
1146
|
-
},
|
|
1147
|
-
/**
|
|
1148
|
-
* All TailorDB clients created, with their namespace and end state.
|
|
1149
|
-
* @returns Created clients array
|
|
1150
|
-
*/
|
|
1151
|
-
get createdClients() {
|
|
1152
|
-
return createdClients;
|
|
1153
|
-
},
|
|
1154
|
-
/** Clear recorded calls while preserving configured query behavior. */
|
|
1155
|
-
clear() {
|
|
1156
|
-
queryObject.mockClear();
|
|
1157
|
-
connect.mockClear();
|
|
1158
|
-
Client.mockClear();
|
|
1159
|
-
createdClients.length = 0;
|
|
1160
|
-
},
|
|
1161
|
-
/** Reset query responses and recorded calls (keeps the mock installed). */
|
|
1162
|
-
reset() {
|
|
1163
|
-
queryObject.mockReset();
|
|
1164
|
-
queryObject.mockImplementation(defaultQuery);
|
|
1165
|
-
connect.mockReset();
|
|
1166
|
-
connect.mockImplementation(defaultConnect);
|
|
1167
|
-
Client.mockReset();
|
|
1168
|
-
Client.mockImplementation(defaultClient);
|
|
1169
|
-
createdClients.length = 0;
|
|
1170
|
-
rules.length = 0;
|
|
1171
|
-
queryResolver = void 0;
|
|
1172
|
-
}
|
|
1173
|
-
}, () => {
|
|
1174
|
-
root.Client = prevClient;
|
|
1175
|
-
});
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
//#endregion
|
|
1179
|
-
//#region src/vitest/mocks/workflow.ts
|
|
1180
|
-
const baseInvokerWait = /* @__PURE__ */ new WeakMap();
|
|
1181
|
-
const baseInvokerResolve = /* @__PURE__ */ new WeakMap();
|
|
1182
|
-
const originalProcedures = /* @__PURE__ */ new WeakMap();
|
|
1183
|
-
function replaceProcedure(target, key, current) {
|
|
1184
|
-
const original = originalProcedures.get(current) ?? current;
|
|
1185
|
-
const defaultImplementation = function(...args) {
|
|
1186
|
-
return Reflect.apply(original, this, args);
|
|
1187
|
-
};
|
|
1188
|
-
const mock = vi.fn(defaultImplementation);
|
|
1189
|
-
originalProcedures.set(mock, original);
|
|
1190
|
-
const record = target;
|
|
1191
|
-
record[key] = mock;
|
|
1192
|
-
return {
|
|
1193
|
-
mock,
|
|
1194
|
-
scoped: {
|
|
1195
|
-
mockClear: () => mock.mockClear(),
|
|
1196
|
-
mockReset: () => mock.mockReset(),
|
|
1197
|
-
restore: () => {
|
|
1198
|
-
if (record[key] === mock) record[key] = current;
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
function replaceStart(definition) {
|
|
1204
|
-
return replaceProcedure(definition, "start", definition.start);
|
|
1205
|
-
}
|
|
1206
|
-
/**
|
|
1207
|
-
* Acquire a disposable mock for workflow operations (`tailor.workflow`).
|
|
1208
|
-
* Restored on dispose.
|
|
1209
|
-
|
|
1210
|
-
* @returns Disposable workflow mock control object
|
|
1211
|
-
* @example
|
|
1212
|
-
* ```typescript
|
|
1213
|
-
* import { mockWorkflow } from "@tailor-platform/sdk/vitest";
|
|
1214
|
-
*
|
|
1215
|
-
* test("job start", async () => {
|
|
1216
|
-
* using wf = mockWorkflow();
|
|
1217
|
-
* const job = wf.job(validateOrder);
|
|
1218
|
-
* job.mockResolvedValue({ valid: true });
|
|
1219
|
-
* await runWorkflowUnderTest();
|
|
1220
|
-
* expect(job).toHaveBeenCalled();
|
|
1221
|
-
* });
|
|
1222
|
-
* ```
|
|
1223
|
-
*/
|
|
1224
|
-
function mockWorkflow() {
|
|
1225
|
-
const root = tailorRoot();
|
|
1226
|
-
const prev = root.workflow;
|
|
1227
|
-
const prevEnv = readWorkflowTestEnv();
|
|
1228
|
-
const jobSpies = /* @__PURE__ */ new Map();
|
|
1229
|
-
const workflowSpies = /* @__PURE__ */ new Map();
|
|
1230
|
-
const waitPointMocks = /* @__PURE__ */ new Map();
|
|
1231
|
-
const keyDispatchers = /* @__PURE__ */ new Map();
|
|
1232
|
-
const scopedMocks = /* @__PURE__ */ new Set();
|
|
1233
|
-
const installKeyDispatcher = (definition) => {
|
|
1234
|
-
const cached = keyDispatchers.get(definition);
|
|
1235
|
-
if (cached) return cached;
|
|
1236
|
-
const invoker = getWaitPointInvoker(definition);
|
|
1237
|
-
if (!invoker) throw new Error("waitPointWith expects a wait point definition created by createWaitPoint or createWaitPoints.");
|
|
1238
|
-
const record = invoker;
|
|
1239
|
-
const prevWait = invoker.wait;
|
|
1240
|
-
const prevResolve = invoker.resolve;
|
|
1241
|
-
const baseWait = baseInvokerWait.get(prevWait) ?? prevWait;
|
|
1242
|
-
const baseResolve = baseInvokerResolve.get(prevResolve) ?? prevResolve;
|
|
1243
|
-
const slot = {
|
|
1244
|
-
perKey: /* @__PURE__ */ new Map(),
|
|
1245
|
-
originalWait: (key, payload) => baseWait.call(invoker, key, payload),
|
|
1246
|
-
originalResolve: (key, executionId, callback) => baseResolve.call(invoker, key, executionId, callback)
|
|
1247
|
-
};
|
|
1248
|
-
const dispatchWait = (key, payload) => {
|
|
1249
|
-
const mock = slot.perKey.get(key);
|
|
1250
|
-
if (!mock) return slot.originalWait(key, payload);
|
|
1251
|
-
return payload === void 0 ? mock.wait() : mock.wait(payload);
|
|
1252
|
-
};
|
|
1253
|
-
const dispatchResolve = async (key, executionId, callback) => {
|
|
1254
|
-
const mock = slot.perKey.get(key);
|
|
1255
|
-
if (!mock) return slot.originalResolve(key, executionId, callback);
|
|
1256
|
-
await mock.resolve(executionId, callback);
|
|
1257
|
-
};
|
|
1258
|
-
baseInvokerWait.set(dispatchWait, baseWait);
|
|
1259
|
-
baseInvokerResolve.set(dispatchResolve, baseResolve);
|
|
1260
|
-
record.wait = dispatchWait;
|
|
1261
|
-
record.resolve = dispatchResolve;
|
|
1262
|
-
const eachSpy = (fn) => {
|
|
1263
|
-
for (const mock of slot.perKey.values()) {
|
|
1264
|
-
const pair = mock;
|
|
1265
|
-
fn(pair.wait);
|
|
1266
|
-
fn(pair.resolve);
|
|
1267
|
-
}
|
|
1268
|
-
};
|
|
1269
|
-
scopedMocks.add({
|
|
1270
|
-
mockClear: () => eachSpy((spy) => spy.mockClear()),
|
|
1271
|
-
mockReset: () => eachSpy((spy) => spy.mockReset()),
|
|
1272
|
-
restore: () => {
|
|
1273
|
-
record.wait = prevWait;
|
|
1274
|
-
record.resolve = prevResolve;
|
|
1275
|
-
keyDispatchers.delete(definition);
|
|
1276
|
-
}
|
|
1277
|
-
});
|
|
1278
|
-
keyDispatchers.set(definition, slot);
|
|
1279
|
-
return slot;
|
|
1280
|
-
};
|
|
1281
|
-
const defaultExecJob = (jobName, _args, _options) => {
|
|
1282
|
-
throw new Error(`No workflow job mock for "${jobName}". Call mockWorkflow().setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`);
|
|
1283
|
-
};
|
|
1284
|
-
const defaultStartWorkflow = async (_workflowName, _args, _options) => {
|
|
1285
|
-
return START_DEFAULT;
|
|
1286
|
-
};
|
|
1287
|
-
const defaultResumeWorkflowExecution = async (executionId) => executionId;
|
|
1288
|
-
const execJobFunction = vi.fn(defaultExecJob);
|
|
1289
|
-
const startWorkflow = vi.fn(defaultStartWorkflow);
|
|
1290
|
-
const resumeWorkflowExecution = vi.fn(defaultResumeWorkflowExecution);
|
|
1291
|
-
const wait = vi.fn((_key, _payload) => null);
|
|
1292
|
-
const resolve = vi.fn(async (_executionId, _key, _callback) => {});
|
|
1293
|
-
const jobFunctionShim = (...call) => {
|
|
1294
|
-
const out = call.length >= 3 ? execJobFunction(call[0], platformSerialize(call[1]), call[2]) : execJobFunction(call[0], platformSerialize(call[1]));
|
|
1295
|
-
return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);
|
|
1296
|
-
};
|
|
1297
|
-
const workflowShim = (...call) => call.length >= 3 ? startWorkflow(call[0], platformSerialize(call[1]), call[2]) : startWorkflow(call[0], platformSerialize(call[1]));
|
|
1298
|
-
const resumeShim = (executionId) => resumeWorkflowExecution(executionId);
|
|
1299
|
-
root.workflow = {
|
|
1300
|
-
execJobFunction: jobFunctionShim,
|
|
1301
|
-
startWorkflow: workflowShim,
|
|
1302
|
-
resumeWorkflowExecution: resumeShim,
|
|
1303
|
-
wait: (key, payload) => wait(key, platformSerialize(payload)),
|
|
1304
|
-
resolve: (executionId, key, callback) => resolve(executionId, key, (payload) => {
|
|
1305
|
-
const out = callback(payload);
|
|
1306
|
-
return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);
|
|
1307
|
-
})
|
|
1308
|
-
};
|
|
1309
|
-
return withDispose({
|
|
1310
|
-
/** The `execJobFunction` `vi.fn`. */
|
|
1311
|
-
execJobFunction,
|
|
1312
|
-
/** The `startWorkflow` `vi.fn`. */
|
|
1313
|
-
startWorkflow,
|
|
1314
|
-
/** The `resumeWorkflowExecution` `vi.fn`. */
|
|
1315
|
-
resumeWorkflowExecution,
|
|
1316
|
-
/** The `wait` `vi.fn`. */
|
|
1317
|
-
wait,
|
|
1318
|
-
/** The `resolve` `vi.fn`. */
|
|
1319
|
-
resolve,
|
|
1320
|
-
/**
|
|
1321
|
-
* Get a stable, typed mock for a workflow job's `start` method.
|
|
1322
|
-
* The real start behavior is used until an implementation or result is configured.
|
|
1323
|
-
* @param definition - Workflow job definition to mock
|
|
1324
|
-
* @returns Typed `start` mock for the definition
|
|
1325
|
-
*/
|
|
1326
|
-
job(definition) {
|
|
1327
|
-
const existing = jobSpies.get(definition);
|
|
1328
|
-
if (existing) return existing;
|
|
1329
|
-
const { mock, scoped } = replaceStart(definition);
|
|
1330
|
-
scopedMocks.add(scoped);
|
|
1331
|
-
jobSpies.set(definition, mock);
|
|
1332
|
-
return mock;
|
|
1333
|
-
},
|
|
1334
|
-
/**
|
|
1335
|
-
* Get a stable, typed mock for a workflow definition's `start` method.
|
|
1336
|
-
* The real start behavior is used until an implementation or result is configured.
|
|
1337
|
-
* @param definition - Workflow definition to mock
|
|
1338
|
-
* @returns Typed `start` mock for the definition
|
|
1339
|
-
*/
|
|
1340
|
-
workflow(definition) {
|
|
1341
|
-
const existing = workflowSpies.get(definition);
|
|
1342
|
-
if (existing) return existing;
|
|
1343
|
-
const { mock, scoped } = replaceStart(definition);
|
|
1344
|
-
workflowSpies.set(definition, mock);
|
|
1345
|
-
scopedMocks.add(scoped);
|
|
1346
|
-
return mock;
|
|
1347
|
-
},
|
|
1348
|
-
/**
|
|
1349
|
-
* Get stable, typed mocks for a wait point's `wait` and `resolve` methods.
|
|
1350
|
-
* @param definition - Wait point definition to mock
|
|
1351
|
-
* @returns Typed wait point mock control object
|
|
1352
|
-
*/
|
|
1353
|
-
waitPoint(definition) {
|
|
1354
|
-
const existing = waitPointMocks.get(definition);
|
|
1355
|
-
if (existing) return existing;
|
|
1356
|
-
const waitReplacement = replaceProcedure(definition, "wait", definition.wait);
|
|
1357
|
-
const resolveReplacement = replaceProcedure(definition, "resolve", definition.resolve);
|
|
1358
|
-
const waitSpy = waitReplacement.mock;
|
|
1359
|
-
const resolveSpy = resolveReplacement.mock;
|
|
1360
|
-
scopedMocks.add(waitReplacement.scoped);
|
|
1361
|
-
scopedMocks.add(resolveReplacement.scoped);
|
|
1362
|
-
const waitPointMock = {
|
|
1363
|
-
wait: waitSpy,
|
|
1364
|
-
resolve: resolveSpy,
|
|
1365
|
-
/**
|
|
1366
|
-
* Invoke the next and subsequent resolve callbacks with a wait payload.
|
|
1367
|
-
* @param payload - Payload originally supplied to the wait point
|
|
1368
|
-
*/
|
|
1369
|
-
setResolvePayload(payload) {
|
|
1370
|
-
resolveSpy.mockImplementation(async (_executionId, callback) => {
|
|
1371
|
-
platformSerialize(await callback(platformSerialize(payload)));
|
|
1372
|
-
});
|
|
1373
|
-
}
|
|
1374
|
-
};
|
|
1375
|
-
waitPointMocks.set(definition, waitPointMock);
|
|
1376
|
-
return waitPointMock;
|
|
1377
|
-
},
|
|
1378
|
-
/**
|
|
1379
|
-
* Get stable, typed mocks for one param binding of a parameterized wait point.
|
|
1380
|
-
* Calls made with other bindings fall through to the platform mock.
|
|
1381
|
-
* @param definition - Parameterized wait point definition to mock
|
|
1382
|
-
* @param params - Param binding to intercept, as passed to `.with()`
|
|
1383
|
-
* @returns Typed wait point mock control object
|
|
1384
|
-
*/
|
|
1385
|
-
waitPointWith(definition, params) {
|
|
1386
|
-
const key = getWaitPointKey(definition.with(params));
|
|
1387
|
-
if (key === void 0) throw new Error("waitPointWith expects a wait point declared with $params. Use waitPoint() for a wait point with a fixed key.");
|
|
1388
|
-
const slot = installKeyDispatcher(definition);
|
|
1389
|
-
const existing = slot.perKey.get(key);
|
|
1390
|
-
if (existing) return existing;
|
|
1391
|
-
const waitSpy = vi.fn((payload) => Promise.resolve(slot.originalWait(key, payload)));
|
|
1392
|
-
const resolveSpy = vi.fn((executionId, callback) => slot.originalResolve(key, executionId, callback));
|
|
1393
|
-
const waitPointMock = {
|
|
1394
|
-
wait: waitSpy,
|
|
1395
|
-
resolve: resolveSpy,
|
|
1396
|
-
/**
|
|
1397
|
-
* Invoke the next and subsequent resolve callbacks with a wait payload.
|
|
1398
|
-
* @param payload - Payload originally supplied to the wait point
|
|
1399
|
-
*/
|
|
1400
|
-
setResolvePayload(payload) {
|
|
1401
|
-
resolveSpy.mockImplementation(async (_executionId, callback) => {
|
|
1402
|
-
platformSerialize(await callback(platformSerialize(payload)));
|
|
1403
|
-
});
|
|
1404
|
-
}
|
|
1405
|
-
};
|
|
1406
|
-
slot.perKey.set(key, waitPointMock);
|
|
1407
|
-
return waitPointMock;
|
|
1408
|
-
},
|
|
1409
|
-
/**
|
|
1410
|
-
* Set a fallback job handler. Called when the enqueue queue is empty.
|
|
1411
|
-
* @param handler - Function returning a result for a job name, args, and options
|
|
1412
|
-
*/
|
|
1413
|
-
setJobHandler(handler) {
|
|
1414
|
-
execJobFunction.mockImplementation((name, args, options) => handler(name, args, options));
|
|
1415
|
-
},
|
|
1416
|
-
/**
|
|
1417
|
-
* Enqueue a single result for the next `execJobFunction` call (FIFO;
|
|
1418
|
-
* takes priority over `setJobHandler`).
|
|
1419
|
-
* @param result - Result to return from the next call
|
|
1420
|
-
*/
|
|
1421
|
-
enqueueResult(result) {
|
|
1422
|
-
execJobFunction.mockImplementationOnce(() => result);
|
|
1423
|
-
},
|
|
1424
|
-
/**
|
|
1425
|
-
* Enqueue results for multiple subsequent `execJobFunction` calls (FIFO).
|
|
1426
|
-
* @param results - Results to enqueue, one per upcoming call
|
|
1427
|
-
*/
|
|
1428
|
-
enqueueResults(...results) {
|
|
1429
|
-
for (const result of results) execJobFunction.mockImplementationOnce(() => result);
|
|
1430
|
-
},
|
|
1431
|
-
/**
|
|
1432
|
-
* All jobs executed via `execJobFunction`, in order.
|
|
1433
|
-
* @returns Started jobs array
|
|
1434
|
-
*/
|
|
1435
|
-
get startedJobs() {
|
|
1436
|
-
return execJobFunction.mock.calls.map(([jobName, args, options]) => ({
|
|
1437
|
-
jobName,
|
|
1438
|
-
args,
|
|
1439
|
-
...options !== void 0 && { options }
|
|
1440
|
-
}));
|
|
1441
|
-
},
|
|
1442
|
-
/**
|
|
1443
|
-
* Configure what `startWorkflow` returns. Pass a string (same id every
|
|
1444
|
-
* call) or `(name, args, options) => string`. Default: a placeholder UUID.
|
|
1445
|
-
* @param handler - Static execution ID or a function returning one
|
|
1446
|
-
*/
|
|
1447
|
-
setStartHandler(handler) {
|
|
1448
|
-
startWorkflow.mockImplementation(typeof handler === "function" ? async (name, args, options) => handler(name, args, options) : async () => handler);
|
|
1449
|
-
},
|
|
1450
|
-
/**
|
|
1451
|
-
* Configure what `resumeWorkflowExecution` returns. Pass a string (same id
|
|
1452
|
-
* every call) or `(executionId) => string`. Default: echoes the input executionId.
|
|
1453
|
-
* @param handler - Static execution ID or a function returning one
|
|
1454
|
-
*/
|
|
1455
|
-
setResumeHandler(handler) {
|
|
1456
|
-
resumeWorkflowExecution.mockImplementation(typeof handler === "function" ? async (executionId) => handler(executionId) : async () => handler);
|
|
1457
|
-
},
|
|
1458
|
-
/**
|
|
1459
|
-
* Configure what `wait` returns. Pass `(key, payload) => unknown` or any
|
|
1460
|
-
* other value to return it for every call. Default: `null`.
|
|
1461
|
-
* @param handler - Static value or a function returning one
|
|
1462
|
-
*/
|
|
1463
|
-
setWaitHandler: ((handler) => {
|
|
1464
|
-
wait.mockImplementation(typeof handler === "function" ? (key, payload) => handler(key, payload) : () => handler);
|
|
1465
|
-
}),
|
|
1466
|
-
/**
|
|
1467
|
-
* Set the `env` passed to job bodies invoked via `createWorkflowJob().start()`.
|
|
1468
|
-
* Cleared on dispose / reset.
|
|
1469
|
-
* @param env - Env passed to job bodies.
|
|
1470
|
-
*/
|
|
1471
|
-
setEnv(env) {
|
|
1472
|
-
writeWorkflowTestEnv({ ...env });
|
|
1473
|
-
},
|
|
1474
|
-
/**
|
|
1475
|
-
* Configure how `resolve` runs the user-supplied callback. Default: callback
|
|
1476
|
-
* is not invoked (records the call only).
|
|
1477
|
-
* @param handler - Function invoked per `resolve` call
|
|
1478
|
-
*/
|
|
1479
|
-
setResolveHandler(handler) {
|
|
1480
|
-
resolve.mockImplementation(async (executionId, key, callback) => {
|
|
1481
|
-
await handler(executionId, key, callback);
|
|
1482
|
-
});
|
|
1483
|
-
},
|
|
1484
|
-
/**
|
|
1485
|
-
* `wait` calls reshaped as `{ key, payload }` for assertions.
|
|
1486
|
-
* @returns Wait call records
|
|
1487
|
-
*/
|
|
1488
|
-
get waitCalls() {
|
|
1489
|
-
return wait.mock.calls.map(([key, payload]) => ({
|
|
1490
|
-
key,
|
|
1491
|
-
payload
|
|
1492
|
-
}));
|
|
1493
|
-
},
|
|
1494
|
-
/**
|
|
1495
|
-
* `resolve` calls reshaped as `{ executionId, key }` for assertions.
|
|
1496
|
-
* @returns Resolve call records
|
|
1497
|
-
*/
|
|
1498
|
-
get resolveCalls() {
|
|
1499
|
-
return resolve.mock.calls.map(([executionId, key]) => ({
|
|
1500
|
-
executionId,
|
|
1501
|
-
key
|
|
1502
|
-
}));
|
|
1503
|
-
},
|
|
1504
|
-
/** Clear recorded calls while preserving configured responses. */
|
|
1505
|
-
clear() {
|
|
1506
|
-
execJobFunction.mockClear();
|
|
1507
|
-
startWorkflow.mockClear();
|
|
1508
|
-
resumeWorkflowExecution.mockClear();
|
|
1509
|
-
wait.mockClear();
|
|
1510
|
-
resolve.mockClear();
|
|
1511
|
-
for (const mock of scopedMocks) mock.mockClear();
|
|
1512
|
-
},
|
|
1513
|
-
/** Reset all workflow responses and recorded calls (keeps the mock installed). */
|
|
1514
|
-
reset() {
|
|
1515
|
-
execJobFunction.mockReset();
|
|
1516
|
-
execJobFunction.mockImplementation(defaultExecJob);
|
|
1517
|
-
startWorkflow.mockReset();
|
|
1518
|
-
startWorkflow.mockImplementation(defaultStartWorkflow);
|
|
1519
|
-
resumeWorkflowExecution.mockReset();
|
|
1520
|
-
resumeWorkflowExecution.mockImplementation(defaultResumeWorkflowExecution);
|
|
1521
|
-
wait.mockReset();
|
|
1522
|
-
wait.mockImplementation(() => null);
|
|
1523
|
-
resolve.mockReset();
|
|
1524
|
-
resolve.mockImplementation(async () => {});
|
|
1525
|
-
for (const mock of scopedMocks) mock.mockReset();
|
|
1526
|
-
clearWorkflowTestEnv();
|
|
1527
|
-
}
|
|
1528
|
-
}, () => {
|
|
1529
|
-
for (const mock of scopedMocks) mock.restore();
|
|
1530
|
-
root.workflow = prev;
|
|
1531
|
-
if (prevEnv !== void 0) writeWorkflowTestEnv(prevEnv);
|
|
1532
|
-
else clearWorkflowTestEnv();
|
|
1533
|
-
});
|
|
1534
|
-
}
|
|
1535
|
-
|
|
1536
|
-
//#endregion
|
|
1537
|
-
//#region src/vitest/workflow-local.ts
|
|
1538
|
-
var PendingStart = class {
|
|
1539
|
-
jobName;
|
|
1540
|
-
args;
|
|
1541
|
-
constructor(jobName, args) {
|
|
1542
|
-
this.jobName = jobName;
|
|
1543
|
-
this.args = args;
|
|
1544
|
-
}
|
|
1545
|
-
};
|
|
1546
|
-
async function runWorkflowLocally(workflow, args, options) {
|
|
1547
|
-
const root = globalThis;
|
|
1548
|
-
const previousTailor = root.tailor;
|
|
1549
|
-
const previousEnv = readWorkflowTestEnv();
|
|
1550
|
-
const hasPreviousEnv = previousEnv !== void 0;
|
|
1551
|
-
const runner = createLocalJobRunner();
|
|
1552
|
-
if (options?.env !== void 0) writeWorkflowTestEnv({ ...options.env });
|
|
1553
|
-
root.tailor = {
|
|
1554
|
-
...previousTailor,
|
|
1555
|
-
workflow: createLocalWorkflowRuntime(previousTailor?.workflow, runner.execJobFunction)
|
|
1556
|
-
};
|
|
1557
|
-
try {
|
|
1558
|
-
return await runner.runJob(workflow.mainJob.name, args);
|
|
1559
|
-
} finally {
|
|
1560
|
-
if (previousTailor) root.tailor = previousTailor;
|
|
1561
|
-
else delete root.tailor;
|
|
1562
|
-
if (options?.env !== void 0) if (hasPreviousEnv) writeWorkflowTestEnv(previousEnv);
|
|
1563
|
-
else clearWorkflowTestEnv();
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
function createLocalJobRunner() {
|
|
1567
|
-
let activeExecution;
|
|
1568
|
-
const execJobFunction = (jobName, args) => {
|
|
1569
|
-
if (!activeExecution) throw new Error(`Cannot start workflow job "${jobName}" outside runWorkflowLocally() job execution.`);
|
|
1570
|
-
if (activeExecution.pending) throw activeExecution.pending;
|
|
1571
|
-
const serializedArgs = platformSerialize(args);
|
|
1572
|
-
const index = activeExecution.cursor;
|
|
1573
|
-
activeExecution.cursor += 1;
|
|
1574
|
-
const cached = activeExecution.records[index];
|
|
1575
|
-
if (cached) {
|
|
1576
|
-
assertSameStart(cached, jobName, serializedArgs);
|
|
1577
|
-
if (cached.status === "rejected") throw cached.error;
|
|
1578
|
-
return platformSerialize(cached.result);
|
|
1579
|
-
}
|
|
1580
|
-
const pending = new PendingStart(jobName, serializedArgs);
|
|
1581
|
-
activeExecution.pending = pending;
|
|
1582
|
-
throw pending;
|
|
1583
|
-
};
|
|
1584
|
-
const runJob = async (name, args) => {
|
|
1585
|
-
const body = getRegisteredJob(name);
|
|
1586
|
-
if (!body) return null;
|
|
1587
|
-
const records = [];
|
|
1588
|
-
for (;;) {
|
|
1589
|
-
const execution = {
|
|
1590
|
-
records,
|
|
1591
|
-
cursor: 0
|
|
1592
|
-
};
|
|
1593
|
-
const previousExecution = activeExecution;
|
|
1594
|
-
activeExecution = execution;
|
|
1595
|
-
try {
|
|
1596
|
-
const out = await body(platformSerialize(args), buildJobContext());
|
|
1597
|
-
if (execution.pending) {
|
|
1598
|
-
await settlePendingStart(records, execution.pending, runJob);
|
|
1599
|
-
continue;
|
|
1600
|
-
}
|
|
1601
|
-
if (execution.cursor !== records.length) throw new Error(`Workflow job start sequence changed while replaying "${name}". Expected ${records.length} start(s), but replay reached ${execution.cursor}.`);
|
|
1602
|
-
return platformSerialize(out);
|
|
1603
|
-
} catch (cause) {
|
|
1604
|
-
const pending = cause instanceof PendingStart ? cause : execution.pending;
|
|
1605
|
-
if (pending) {
|
|
1606
|
-
await settlePendingStart(records, pending, runJob);
|
|
1607
|
-
continue;
|
|
1608
|
-
}
|
|
1609
|
-
throw cause;
|
|
1610
|
-
} finally {
|
|
1611
|
-
activeExecution = previousExecution;
|
|
1612
|
-
}
|
|
1613
|
-
}
|
|
1614
|
-
};
|
|
1615
|
-
return {
|
|
1616
|
-
runJob,
|
|
1617
|
-
execJobFunction
|
|
1618
|
-
};
|
|
1619
|
-
}
|
|
1620
|
-
async function settlePendingStart(records, pending, runJob) {
|
|
1621
|
-
try {
|
|
1622
|
-
records.push({
|
|
1623
|
-
jobName: pending.jobName,
|
|
1624
|
-
args: pending.args,
|
|
1625
|
-
status: "fulfilled",
|
|
1626
|
-
result: await runJob(pending.jobName, pending.args)
|
|
1627
|
-
});
|
|
1628
|
-
} catch (error) {
|
|
1629
|
-
records.push({
|
|
1630
|
-
jobName: pending.jobName,
|
|
1631
|
-
args: pending.args,
|
|
1632
|
-
status: "rejected",
|
|
1633
|
-
error
|
|
1634
|
-
});
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
function assertSameStart(record, jobName, args) {
|
|
1638
|
-
if (record.jobName === jobName && JSON.stringify(record.args) === JSON.stringify(args)) return;
|
|
1639
|
-
throw new Error(`Workflow job start sequence changed while replaying. Expected ${record.jobName}(${JSON.stringify(record.args)}), but got ${jobName}(${JSON.stringify(args)}).`);
|
|
1640
|
-
}
|
|
1641
|
-
function createLocalWorkflowRuntime(previous, execJobFunction) {
|
|
1642
|
-
const startWorkflow = async (name, args, options) => {
|
|
1643
|
-
if (previous) return await previous.startWorkflow(name, args, options);
|
|
1644
|
-
platformSerialize(args);
|
|
1645
|
-
return START_DEFAULT;
|
|
1646
|
-
};
|
|
1647
|
-
const resumeWorkflowExecution = async (executionId) => {
|
|
1648
|
-
if (previous) return await previous.resumeWorkflowExecution(executionId);
|
|
1649
|
-
return executionId;
|
|
1650
|
-
};
|
|
1651
|
-
return {
|
|
1652
|
-
execJobFunction,
|
|
1653
|
-
startWorkflow,
|
|
1654
|
-
resumeWorkflowExecution,
|
|
1655
|
-
wait: (key, payload) => {
|
|
1656
|
-
if (previous) return previous.wait(key, payload);
|
|
1657
|
-
throw new Error(`No wait handler for "${key}". Acquire mockWorkflow() and call setWaitHandler(...).`);
|
|
1658
|
-
},
|
|
1659
|
-
resolve: async (executionId, key, callback) => {
|
|
1660
|
-
if (previous) {
|
|
1661
|
-
await previous.resolve(executionId, key, callback);
|
|
1662
|
-
return;
|
|
1663
|
-
}
|
|
1664
|
-
throw new Error("No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).");
|
|
1665
|
-
}
|
|
1666
|
-
};
|
|
1667
|
-
}
|
|
1668
|
-
|
|
1669
|
-
//#endregion
|
|
1670
|
-
//#region src/vitest/mock-kysely.ts
|
|
1671
|
-
/**
|
|
1672
|
-
* Kysely-layer mock for unit testing.
|
|
1673
|
-
*
|
|
1674
|
-
* Builds a real Kysely instance backed by a mock driver: queries compile and
|
|
1675
|
-
* type-check normally, but execution returns staged rows and records every
|
|
1676
|
-
* query for assertions.
|
|
1677
|
-
*/
|
|
1678
|
-
function unwrapValue(node) {
|
|
1679
|
-
return ValueNode.is(node) ? node.value : node;
|
|
1680
|
-
}
|
|
1681
|
-
function insertRows(node) {
|
|
1682
|
-
if (!InsertQueryNode.is(node)) throw new Error(`insertRows: expected InsertQueryNode, got ${node.kind}`);
|
|
1683
|
-
const columns = node.columns;
|
|
1684
|
-
const valuesNode = node.values;
|
|
1685
|
-
if (columns === void 0 || valuesNode === void 0 || !ValuesNode.is(valuesNode)) throw new Error("insertRows: unsupported insert shape; inspect query.node instead");
|
|
1686
|
-
return valuesNode.values.map((row) => {
|
|
1687
|
-
if (!PrimitiveValueListNode.is(row) && !ValueListNode.is(row)) throw new Error("insertRows: unsupported insert shape; inspect query.node instead");
|
|
1688
|
-
const values = PrimitiveValueListNode.is(row) ? row.values : row.values.map(unwrapValue);
|
|
1689
|
-
const result = {};
|
|
1690
|
-
columns.forEach((col, i) => {
|
|
1691
|
-
result[col.column.name] = values[i];
|
|
1692
|
-
});
|
|
1693
|
-
return result;
|
|
1694
|
-
});
|
|
1695
|
-
}
|
|
1696
|
-
function insertValues(node) {
|
|
1697
|
-
const rows = insertRows(node);
|
|
1698
|
-
if (rows.length !== 1) throw new Error(`insertValues: query inserts ${rows.length} rows; use insertRows() for multi-row inserts`);
|
|
1699
|
-
return assertDefined(rows[0], "insertValues: first row missing");
|
|
1700
|
-
}
|
|
1701
|
-
function updateValues(node) {
|
|
1702
|
-
if (!UpdateQueryNode.is(node)) throw new Error(`updateValues: expected UpdateQueryNode, got ${node.kind}`);
|
|
1703
|
-
if (node.updates === void 0) throw new Error("updateValues: unsupported update shape; inspect query.node instead");
|
|
1704
|
-
const result = {};
|
|
1705
|
-
for (const update of node.updates) {
|
|
1706
|
-
const col = update.column;
|
|
1707
|
-
const name = ColumnNode.is(col) ? col.column.name : ReferenceNode.is(col) && ColumnNode.is(col.column) ? col.column.column.name : void 0;
|
|
1708
|
-
if (name === void 0) throw new Error("updateValues: unsupported update shape; inspect query.node instead");
|
|
1709
|
-
result[name] = unwrapValue(update.value);
|
|
1710
|
-
}
|
|
1711
|
-
return result;
|
|
1712
|
-
}
|
|
1713
|
-
function toExecutedQuery(compiledQuery) {
|
|
1714
|
-
const node = compiledQuery.query;
|
|
1715
|
-
return {
|
|
1716
|
-
kind: node.kind,
|
|
1717
|
-
sql: compiledQuery.sql,
|
|
1718
|
-
parameters: compiledQuery.parameters,
|
|
1719
|
-
node,
|
|
1720
|
-
insertRows: () => insertRows(node),
|
|
1721
|
-
insertValues: () => insertValues(node),
|
|
1722
|
-
updateValues: () => updateValues(node)
|
|
1723
|
-
};
|
|
1724
|
-
}
|
|
1725
|
-
function toStagedResult(result) {
|
|
1726
|
-
if (Array.isArray(result)) return {
|
|
1727
|
-
rows: result,
|
|
1728
|
-
numAffectedRows: void 0
|
|
1729
|
-
};
|
|
1730
|
-
return {
|
|
1731
|
-
rows: result.rows ?? [],
|
|
1732
|
-
numAffectedRows: result.numAffectedRows === void 0 ? void 0 : BigInt(result.numAffectedRows)
|
|
1733
|
-
};
|
|
1734
|
-
}
|
|
1735
|
-
var MockState = class {
|
|
1736
|
-
executed = [];
|
|
1737
|
-
queue = [];
|
|
1738
|
-
resolver;
|
|
1739
|
-
enqueue(...results) {
|
|
1740
|
-
this.queue.push(...results);
|
|
1741
|
-
}
|
|
1742
|
-
setResolver(resolver) {
|
|
1743
|
-
this.resolver = resolver;
|
|
1744
|
-
}
|
|
1745
|
-
next(query) {
|
|
1746
|
-
const resolved = this.resolver?.(query);
|
|
1747
|
-
if (resolved !== void 0) return toStagedResult(resolved);
|
|
1748
|
-
const queued = this.queue.shift();
|
|
1749
|
-
return queued === void 0 ? {
|
|
1750
|
-
rows: [],
|
|
1751
|
-
numAffectedRows: void 0
|
|
1752
|
-
} : toStagedResult(queued);
|
|
1753
|
-
}
|
|
1754
|
-
reset() {
|
|
1755
|
-
this.executed.length = 0;
|
|
1756
|
-
this.queue.length = 0;
|
|
1757
|
-
this.resolver = void 0;
|
|
1758
|
-
}
|
|
1759
|
-
};
|
|
1760
|
-
var MockConnection = class {
|
|
1761
|
-
state;
|
|
1762
|
-
constructor(state) {
|
|
1763
|
-
this.state = state;
|
|
1764
|
-
}
|
|
1765
|
-
async executeQuery(compiledQuery) {
|
|
1766
|
-
const query = toExecutedQuery(compiledQuery);
|
|
1767
|
-
this.state.executed.push(query);
|
|
1768
|
-
const { rows, numAffectedRows } = this.state.next(query);
|
|
1769
|
-
return {
|
|
1770
|
-
rows,
|
|
1771
|
-
numAffectedRows: numAffectedRows ?? BigInt(rows.length)
|
|
1772
|
-
};
|
|
1773
|
-
}
|
|
1774
|
-
streamQuery() {
|
|
1775
|
-
throw new Error("createKyselyMock: streaming is not supported");
|
|
1776
|
-
}
|
|
1777
|
-
};
|
|
1778
|
-
var MockDriver = class {
|
|
1779
|
-
state;
|
|
1780
|
-
constructor(state) {
|
|
1781
|
-
this.state = state;
|
|
1782
|
-
}
|
|
1783
|
-
async init() {}
|
|
1784
|
-
async acquireConnection() {
|
|
1785
|
-
return new MockConnection(this.state);
|
|
1786
|
-
}
|
|
1787
|
-
async beginTransaction() {}
|
|
1788
|
-
async commitTransaction() {}
|
|
1789
|
-
async rollbackTransaction() {}
|
|
1790
|
-
async releaseConnection() {}
|
|
1791
|
-
async destroy() {}
|
|
1792
|
-
};
|
|
1793
|
-
function byKind(state, kind) {
|
|
1794
|
-
return state.executed.filter((query) => query.kind === kind);
|
|
1795
|
-
}
|
|
1796
|
-
/**
|
|
1797
|
-
* Create a mock Kysely instance for unit-testing code that runs Kysely queries.
|
|
1798
|
-
* Pass the namespace schema as the type argument, e.g.
|
|
1799
|
-
* `createKyselyMock<Namespace["main-db"]>()`.
|
|
1800
|
-
* @returns A {@link KyselyMock} with the mock `db`, recorded queries, and result staging.
|
|
1801
|
-
*/
|
|
1802
|
-
function createKyselyMock() {
|
|
1803
|
-
const state = new MockState();
|
|
1804
|
-
const kysely = new Kysely({ dialect: {
|
|
1805
|
-
createDriver: () => new MockDriver(state),
|
|
1806
|
-
createQueryCompiler: () => new PostgresQueryCompiler(),
|
|
1807
|
-
createAdapter: () => new PostgresAdapter(),
|
|
1808
|
-
createIntrospector: (db) => new PostgresIntrospector(db)
|
|
1809
|
-
} });
|
|
1810
|
-
return {
|
|
1811
|
-
db: kysely,
|
|
1812
|
-
get executedQueries() {
|
|
1813
|
-
return state.executed;
|
|
1814
|
-
},
|
|
1815
|
-
get selects() {
|
|
1816
|
-
return byKind(state, "SelectQueryNode");
|
|
1817
|
-
},
|
|
1818
|
-
get inserts() {
|
|
1819
|
-
return byKind(state, "InsertQueryNode");
|
|
1820
|
-
},
|
|
1821
|
-
get updates() {
|
|
1822
|
-
return byKind(state, "UpdateQueryNode");
|
|
1823
|
-
},
|
|
1824
|
-
get deletes() {
|
|
1825
|
-
return byKind(state, "DeleteQueryNode");
|
|
1826
|
-
},
|
|
1827
|
-
enqueueResult: (result) => state.enqueue(result),
|
|
1828
|
-
enqueueResults: (...results) => state.enqueue(...results),
|
|
1829
|
-
setQueryResolver: (resolver) => state.setResolver(resolver),
|
|
1830
|
-
withTx: (fn) => kysely.transaction().execute(fn),
|
|
1831
|
-
reset: () => state.reset(),
|
|
1832
|
-
[Symbol.dispose]: () => state.reset()
|
|
1833
|
-
};
|
|
1834
|
-
}
|
|
1835
|
-
|
|
1836
|
-
//#endregion
|
|
1837
|
-
//#region src/vitest/pglite-kysely.ts
|
|
1838
|
-
/**
|
|
1839
|
-
* Kysely adapter for running migration scripts against PGlite.
|
|
1840
|
-
*
|
|
1841
|
-
* Accepts the PGlite client structurally so the SDK does not depend on
|
|
1842
|
-
* `@electric-sql/pglite`; users install it themselves as a devDependency.
|
|
1843
|
-
*/
|
|
1844
|
-
var PGliteConnection = class {
|
|
1845
|
-
#client;
|
|
1846
|
-
constructor(client) {
|
|
1847
|
-
this.#client = client;
|
|
1848
|
-
}
|
|
1849
|
-
async executeQuery(compiledQuery) {
|
|
1850
|
-
const result = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]);
|
|
1851
|
-
return {
|
|
1852
|
-
rows: result.rows,
|
|
1853
|
-
numAffectedRows: BigInt(result.affectedRows ?? 0)
|
|
1854
|
-
};
|
|
1855
|
-
}
|
|
1856
|
-
streamQuery() {
|
|
1857
|
-
throw new Error("createKyselyPGlite: streaming is not supported");
|
|
1858
|
-
}
|
|
1859
|
-
};
|
|
1860
|
-
var PGliteDriver = class {
|
|
1861
|
-
#client;
|
|
1862
|
-
constructor(client) {
|
|
1863
|
-
this.#client = client;
|
|
1864
|
-
}
|
|
1865
|
-
async init() {}
|
|
1866
|
-
async acquireConnection() {
|
|
1867
|
-
return new PGliteConnection(this.#client);
|
|
1868
|
-
}
|
|
1869
|
-
async beginTransaction(connection, settings) {
|
|
1870
|
-
const parts = settings.isolationLevel ? ["start transaction", `isolation level ${settings.isolationLevel}`] : ["begin"];
|
|
1871
|
-
if (settings.accessMode) parts.push(settings.accessMode);
|
|
1872
|
-
await connection.executeQuery(CompiledQuery.raw(parts.join(" ")));
|
|
1873
|
-
}
|
|
1874
|
-
async commitTransaction(connection) {
|
|
1875
|
-
await connection.executeQuery(CompiledQuery.raw("commit"));
|
|
1876
|
-
}
|
|
1877
|
-
async rollbackTransaction(connection) {
|
|
1878
|
-
await connection.executeQuery(CompiledQuery.raw("rollback"));
|
|
1879
|
-
}
|
|
1880
|
-
async releaseConnection() {}
|
|
1881
|
-
async destroy() {
|
|
1882
|
-
await this.#client.close();
|
|
1883
|
-
}
|
|
1884
|
-
};
|
|
1885
|
-
/**
|
|
1886
|
-
* Create a Kysely instance backed by a PGlite in-memory Postgres, for
|
|
1887
|
-
* executing a migration script's queries against real data in tests.
|
|
1888
|
-
* Pass the migration's schema as the type argument, e.g.
|
|
1889
|
-
* `createKyselyPGlite<Database>(new PGlite())`.
|
|
1890
|
-
*
|
|
1891
|
-
* PGlite runs full PostgreSQL while TailorDB supports a subset of it, so a
|
|
1892
|
-
* statement passing here can still be rejected by the platform; keep a
|
|
1893
|
-
* statement-level test (see `createKyselyMock`) alongside.
|
|
1894
|
-
* @param client - A `PGlite` instance from `@electric-sql/pglite`
|
|
1895
|
-
* @returns A Kysely instance that executes queries on the client and closes it on `destroy()`
|
|
1896
|
-
* @example
|
|
1897
|
-
* ```typescript
|
|
1898
|
-
* // migrations/0005/migrate.test.ts
|
|
1899
|
-
* import { PGlite } from "@electric-sql/pglite";
|
|
1900
|
-
* import { createKyselyPGlite } from "@tailor-platform/sdk/vitest";
|
|
1901
|
-
* import type { Database } from "./db";
|
|
1902
|
-
* import { main } from "./migrate";
|
|
1903
|
-
*
|
|
1904
|
-
* const db = createKyselyPGlite<Database>(new PGlite());
|
|
1905
|
-
* // create tables matching db.ts, insert rows, then:
|
|
1906
|
-
* await db.transaction().execute((trx) => main(trx));
|
|
1907
|
-
* ```
|
|
1908
|
-
*/
|
|
1909
|
-
function createKyselyPGlite(client) {
|
|
1910
|
-
return new Kysely({ dialect: {
|
|
1911
|
-
createAdapter: () => new PostgresAdapter(),
|
|
1912
|
-
createDriver: () => new PGliteDriver(client),
|
|
1913
|
-
createIntrospector: (db) => new PostgresIntrospector(db),
|
|
1914
|
-
createQueryCompiler: () => new PostgresQueryCompiler()
|
|
1915
|
-
} });
|
|
1916
|
-
}
|
|
1917
|
-
|
|
1918
|
-
//#endregion
|
|
1919
|
-
//#region src/vitest/index.ts
|
|
1920
|
-
/**
|
|
1921
|
-
* Creates Vitest plugins that emulate the Tailor Platform function runtime environment.
|
|
1922
|
-
*
|
|
1923
|
-
* **Beta:** This API may change in future releases.
|
|
1924
|
-
*
|
|
1925
|
-
* ## What it does
|
|
1926
|
-
*
|
|
1927
|
-
* 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules
|
|
1928
|
-
* (and bare builtins like `crypto`, `fs`) in non-test source files are replaced
|
|
1929
|
-
* with code that throws an error with a suggestion for the Web Standard API alternative.
|
|
1930
|
-
* Test files are exempt and can use `node:*` freely. Test file patterns are read
|
|
1931
|
-
* from the resolved Vitest config (`test.include`).
|
|
1932
|
-
*
|
|
1933
|
-
* 2. **Node.js globals removal** (environment + setup) — Only globals available in the
|
|
1934
|
-
* Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs
|
|
1935
|
-
* from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,
|
|
1936
|
-
* `__dirname`, `__filename`, etc.) are removed. `performance` is removed per-test
|
|
1937
|
-
* via beforeEach/afterEach since Vitest needs it during initialization.
|
|
1938
|
-
*
|
|
1939
|
-
* 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with
|
|
1940
|
-
* control objects: `mockTailordb`, `mockWorkflow`, `mockSecretmanager`,
|
|
1941
|
-
* `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`,
|
|
1942
|
-
* `mockLogger`. Each
|
|
1943
|
-
* provides response configuration, call recording, and reset.
|
|
1944
|
-
*
|
|
1945
|
-
* 4. **Environment resolution** — Rewrites `environment: "tailor-runtime"` to the
|
|
1946
|
-
* absolute path of the bundled environment module via the config hook.
|
|
1947
|
-
*
|
|
1948
|
-
* ## Known limitations
|
|
1949
|
-
*
|
|
1950
|
-
* - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal
|
|
1951
|
-
* runner depends on them. On the real Tailor Platform runtime, they do not exist.
|
|
1952
|
-
* - **Dynamic `import()`** of bundled files bypasses the transform hook since
|
|
1953
|
-
* those files are loaded through Node.js native loader.
|
|
1954
|
-
* ## Options
|
|
1955
|
-
*
|
|
1956
|
-
* - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values
|
|
1957
|
-
* into `mockSecretmanager` so `getSecret()` returns the configured values.
|
|
1958
|
-
* @example
|
|
1959
|
-
* ```typescript
|
|
1960
|
-
* // vitest.config.ts
|
|
1961
|
-
* import { defineConfig } from "vitest/config";
|
|
1962
|
-
* import { tailorRuntime } from "@tailor-platform/sdk/vitest";
|
|
1963
|
-
*
|
|
1964
|
-
* export default defineConfig({
|
|
1965
|
-
* plugins: [tailorRuntime({ config: "./tailor.config.ts" })],
|
|
1966
|
-
* test: {
|
|
1967
|
-
* environment: "tailor-runtime",
|
|
1968
|
-
* },
|
|
1969
|
-
* });
|
|
1970
|
-
* ```
|
|
1971
|
-
* @param options - Optional configuration
|
|
1972
|
-
* @param options.config - Path to tailor.config.ts to load SecretManager values into mock
|
|
1973
|
-
* @returns Array of Vite plugins
|
|
1974
|
-
*/
|
|
1975
|
-
function tailorRuntime(options) {
|
|
1976
|
-
return [createBlockPlugin(), createEnvironmentPlugin(options)];
|
|
1977
|
-
}
|
|
1978
|
-
|
|
1979
|
-
//#endregion
|
|
1980
|
-
export { createKyselyMock, createKyselyPGlite, mockAigateway, mockAuthconnection, mockFile, mockIconv, mockIdp, mockLogger, mockSecretmanager, mockTailordb, mockWorkflow, runWorkflowLocally, tailorRuntime };
|
|
1
|
+
import{i as e,t}from"../registry-HlEaGvl5.mjs";import{a as n,c as r,i,o as a,s as o,u as s}from"../wait-point-invoker-eiP-IIux.mjs";import{t as c}from"../assert-WeXvmG4j.mjs";import{n as l,t as u}from"../node-builtins-oBl7EbyV.mjs";import{t as d}from"../platform-serialize-DkiTdHOt.mjs";import{i as f,n as p,r as m,t as h}from"../secretmanager-5olfnI1b.mjs";import{isEqual as g}from"es-toolkit";import{fileURLToPath as _}from"node:url";import{ColumnNode as v,CompiledQuery as y,InsertQueryNode as b,Kysely as x,PostgresAdapter as S,PostgresIntrospector as C,PostgresQueryCompiler as w,PrimitiveValueListNode as T,ReferenceNode as E,UpdateQueryNode as D,ValueListNode as O,ValueNode as k,ValuesNode as A}from"kysely";import{dirname as j,isAbsolute as M,matchesGlob as N,relative as P,resolve as F}from"node:path";import{vi as I}from"vitest";function isBlockedModule(e){return l(e)}function getBlockedMessage(e){return u(e)}const L=[`**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}`],R=new Set([`ImportDeclaration`,`ExportNamedDeclaration`,`ExportAllDeclaration`]),z=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.yield.let.static.implements.interface.package.private.protected.public.await.arguments.eval`.split(`.`)),B=/^[A-Za-z_$]/,V=/^[A-Za-z0-9_$]*$/;function isSafeBindingName(e){if(z.has(e)||e.length===0)return!1;let t=e[0];return t!==void 0&&B.test(t)&&V.test(e.slice(1))}function buildBlockedReplacement(e,t){let n=JSON.stringify(t),r=`throw new Error(${n});`,i=`(() => { throw new Error(${n}); })()`;if(e.type===`ExportNamedDeclaration`){let t=e.specifiers??[],n=[];for(let e of t){let t=e.exported?.name;if(typeof t==`string`){if(t==="default"){n.push(`export default ${i};`);continue}if(!isSafeBindingName(t))return r;n.push(`export const ${t} = ${i};`)}}return n.length>0?n.join(` `):r}if(e.type===`ExportAllDeclaration`){let t=e.exported?.name;return typeof t==`string`&&isSafeBindingName(t)?`export const ${t} = ${i};`:r}return r}function createBlockPlugin(){let isTestFile=()=>!1,isUserSourceFile=()=>!1;return{name:`tailor-runtime-block-node`,configResolved(e){let t=e.test,n=t?.root??e.root,toAbsolutePaths=(e,t)=>(Array.isArray(e)?e:e?[e]:[]).map(e=>F(t,e)),r=new Set([...toAbsolutePaths(t?.setupFiles,n),...toAbsolutePaths(t?.globalSetup,n)]),i=[{root:n,patterns:t?.include??L}];for(let e of t?.projects??[]){let t=e.test;if(!t)continue;let a=t.root??n;for(let e of toAbsolutePaths(t.setupFiles,a))r.add(e);for(let e of toAbsolutePaths(t.globalSetup,a))r.add(e);i.push({root:a,patterns:t.include??L})}isTestFile=e=>r.has(e)?!0:i.some(({root:t,patterns:n})=>{let r=M(e)?P(t,e):e;return n.some(e=>N(r,e))}),isUserSourceFile=e=>{if(!M(e))return!1;let t=P(n,e);return t!==``&&!t.startsWith(`..`)&&!M(t)}},transform(e,t){let n=t.search(/[?#]/),r=n===-1?t:t.slice(0,n);if(isTestFile(r)||r.includes(`node_modules`)||!isUserSourceFile(r))return;let i;try{i=this.parse(e)}catch{return}let a=[];for(let e of i.body){if(!R.has(e.type))continue;let t=e.source?.value;typeof t==`string`&&isBlockedModule(t)&&a.push({start:e.start,end:e.end,replacement:buildBlockedReplacement(e,getBlockedMessage(t))})}if(a.length===0)return;let o=e;for(let e of a.toSorted((e,t)=>t.start-e.start))o=o.slice(0,e.start)+e.replacement+o.slice(e.end);return{code:o,map:null}}}}const H=`tailor-runtime`;function createEnvironmentPlugin(e){let t=j(_(import.meta.url)),n=F(t,`environment.mjs`),r=F(t,`setup.mjs`);return{name:`tailor-runtime-environment`,config(t){let i=t.test,a=!1;if(i?.environment===H&&(i.environment=n,a=!0),i?.projects)for(let e of i.projects){let t=e.test;t?.environment===H&&(t.environment=n,a=!0)}if(delete process.env.__TAILOR_RUNTIME_CONFIG,e?.config&&a){let n=t.root??process.cwd(),r=F(n,e.config);process.env.__TAILOR_RUNTIME_CONFIG=r}return i&&typeof i.setupFiles==`string`&&(i.setupFiles=[i.setupFiles]),{test:{setupFiles:[r]}}}}}function mockAigateway(e={}){let t=p(),n=t.aigateway,r={...e.urls};async function defaultGet(e){let t=r[e];if(t===void 0)throw Error(`No AI Gateway registered for "${e}". Acquire mockAigateway() and call setUrls(...).`);return{url:t}}let i=I.fn(defaultGet);return t.aigateway={get:i},f({get:i,setUrls(e){r=e},setUrl(e,t){r={...r,[e]:t}},get calls(){return i.mock.calls.map(([e])=>({name:e}))},clear(){i.mockClear()},reset(){r={},i.mockReset(),i.mockImplementation(defaultGet)}},()=>{t.aigateway=n})}function mockAuthconnection(e={}){let t=p(),n=t.authconnection,r={...e.tokens};async function defaultGetConnectionToken(t){let n=r[t];if(n)return n;if(e.onUnhandled===`error`)throw Error(`No AuthConnection token configured for "${t}"`);return{access_token:`mock-token`}}let i=I.fn(defaultGetConnectionToken);return t.authconnection={getConnectionToken:i},f({getConnectionToken:i,setTokens(e){r=e},setToken(e,t){r={...r,[e]:t}},get calls(){return i.mock.calls.map(([e])=>({connectionName:e}))},clear(){i.mockClear()},reset(){r={},i.mockReset(),i.mockImplementation(defaultGetConnectionToken)}},()=>{t.authconnection=n})}const U=[`upload`,`download`,`downloadAsBase64`,`delete`,`getMetadata`,`downloadStream`,`uploadStream`],W={upload:{metadata:{fileSize:0,sha256sum:``}},download:{data:new Uint8Array,metadata:{contentType:``,fileSize:0,sha256sum:``,lastUploadedAt:``}},downloadAsBase64:{data:``,metadata:{contentType:``,fileSize:0,sha256sum:``,lastUploadedAt:``}},getMetadata:{contentType:``,fileSize:0,sha256sum:``,urlPath:``},downloadStream:null,uploadStream:{metadata:{fileSize:0,sha256sum:``}}};function mockFile(e={}){let t=m(),n=t.file,{onUnhandled:r=`fallback`}=e,i=[],a=[],resolver=()=>null;function handle(e,t,n,a,o){if(i.length>0)return i.shift();let s=resolver(e,{method:e,namespace:t,tableName:n,fieldName:a,recordId:o});if(s!=null)return s;if(r===`error`)throw Error(`No File mock configured for "${e}"`);let c=W[e];return c===void 0?void 0:structuredClone(c)}let o=I.fn(async(...e)=>{let[t,n,r,i]=e;return handle(`upload`,t,n,r,i)}),s=I.fn(async(...e)=>handle(`download`,...e)),c=I.fn(async(...e)=>handle(`downloadAsBase64`,...e)),l=I.fn(async(...e)=>{handle(`delete`,...e)}),u=I.fn(async(...e)=>handle(`getMetadata`,...e)),d=I.fn(async(...e)=>handle(`downloadStream`,...e)??{body:new ReadableStream({start(e){e.close()}}),metadata:{contentType:``,fileSize:0,sha256sum:``,lastUploadedAt:``}}),p=I.fn(async(...e)=>{let[t,n,r,i]=e;return handle(`uploadStream`,t,n,r,i)}),h={upload:o,download:s,downloadAsBase64:c,delete:l,getMetadata:u,downloadStream:d,uploadStream:p};function track(e,t){return function(...n){return a.push({method:e,namespace:n[0],tableName:n[1],fieldName:n[2],recordId:n[3]}),t.apply(this,n)}}t.file={upload:track(`upload`,o),download:track(`download`,s),downloadAsBase64:track(`downloadAsBase64`,c),delete:track(`delete`,l),getMetadata:track(`getMetadata`,u),downloadStream:track(`downloadStream`,d),uploadStream:track(`uploadStream`,p)};function allMocks(){return U.map(e=>h[e])}let g={...h,setResolver(e){resolver=e},enqueueResult(e){i.push(e)},enqueueResults(...e){i.push(...e)},get calls(){return a},clear(){a.length=0;for(let e of allMocks())e.mockClear()},reset(){i.length=0,a.length=0,resolver=()=>null;for(let e of allMocks())e.mockReset()}};return f(g,()=>{t.file=n})}function isUtf8(e){return e===`UTF8`||e===`UTF-8`}function defaultIconvResult(e,t){switch(e){case`convert`:case`convertBuffer`:return isUtf8(t[2])?``:new Uint8Array;case`decode`:return``;case`encode`:return isUtf8(t[1])?``:new Uint8Array;case`encodings`:return[]}}function mockIconv(e={}){let t=p(),n=t.iconv,r=null,i=[];function resolve(t,n){if(r){let e=r(t,n);if(e!=null)return e}if(e.onUnhandled===`error`)throw Error(`No Iconv mock behavior configured for "${t}"`);return defaultIconvResult(t,n)}function defaultConvert(e,t,n){return resolve(`convert`,[e,t,n])}function defaultConvertBuffer(e,t,n){return resolve(`convertBuffer`,[e,t,n])}function defaultDecode(e,t){return resolve(`decode`,[e,t])}function defaultEncode(e,t){return resolve(`encode`,[e,t])}function defaultEncodings(){return resolve(`encodings`,[])}let a=I.fn(defaultConvert),o=I.fn(defaultConvertBuffer),s=I.fn(defaultDecode),c=I.fn(defaultEncode),l=I.fn(defaultEncodings);function track(e,t){return function(...n){return i.push({method:e,args:[...n]}),t.apply(this,n)}}let u=track(`convert`,a),d=track(`convertBuffer`,o),m=track(`decode`,s),h=track(`encode`,c),g=track(`encodings`,l);class MockIconv{#e;#t;constructor(e,t){this.#e=e,this.#t=t}convert(e){return u.call(this,e,this.#e,this.#t)}}t.iconv={convert:u,convertBuffer:d,decode:m,encode:h,encodings:g,Iconv:MockIconv};function clear(){i.length=0,a.mockClear(),o.mockClear(),s.mockClear(),c.mockClear(),l.mockClear()}return f({convert:a,convertBuffer:o,decode:s,encode:c,encodings:l,setResolver(e){r=e},get calls(){return i},clear,reset(){r=null,i.length=0,a.mockReset(),a.mockImplementation(defaultConvert),o.mockReset(),o.mockImplementation(defaultConvertBuffer),s.mockReset(),s.mockImplementation(defaultDecode),c.mockReset(),c.mockImplementation(defaultEncode),l.mockReset(),l.mockImplementation(defaultEncodings)}},()=>{t.iconv=n})}const G=[`users`,`user`,`userByName`,`createUser`,`updateUser`,`deleteUser`,`sendPasswordResetEmail`,`unenrollMfa`],K={id:`mock-id`,name:`mock-user`,disabled:!1,mfaEnrolled:!1,mfaFactorIds:[]},q={users:{users:[],nextPageToken:null,totalCount:0},user:K,userByName:K,createUser:K,updateUser:K,deleteUser:!0,sendPasswordResetEmail:!0,unenrollMfa:!0};function mockIdp(e={}){let t=p(),n=t.idp,{onUnhandled:r=`fallback`}=e,i=[],a=[],resolver=()=>null,o=new Map;function compatibilityArgs(e,t){return e===`users`&&t.length===0?[void 0]:t}function handle(e,t,n){if(i.length>0)return i.shift();let a=resolver(e,compatibilityArgs(e,t),n);if(a!=null)return a;if(r===`error`)throw Error(`No IdP mock configured for "${n}.${e}"`);return structuredClone(q[e])}function createNamespaceMocks(e){return{users:I.fn(async(...t)=>handle(`users`,t,e)),user:I.fn(async(...t)=>handle(`user`,t,e)),userByName:I.fn(async(...t)=>handle(`userByName`,t,e)),createUser:I.fn(async(...t)=>handle(`createUser`,t,e)),updateUser:I.fn(async(...t)=>handle(`updateUser`,t,e)),deleteUser:I.fn(async(...t)=>handle(`deleteUser`,t,e)),sendPasswordResetEmail:I.fn(async(...t)=>handle(`sendPasswordResetEmail`,t,e)),unenrollMfa:I.fn(async(...t)=>handle(`unenrollMfa`,t,e))}}function namespace(e){let t=o.get(e);if(t)return t;let n=createNamespaceMocks(e);return o.set(e,n),n}function track(e,t,n){return function(...r){return a.push({method:e,args:[...compatibilityArgs(e,r)],namespace:n}),t.apply(this,r)}}let defaultClient=function(e){let t=namespace(e.namespace);this.users=track(`users`,t.users,e.namespace),this.user=track(`user`,t.user,e.namespace),this.userByName=track(`userByName`,t.userByName,e.namespace),this.createUser=track(`createUser`,t.createUser,e.namespace),this.updateUser=track(`updateUser`,t.updateUser,e.namespace),this.deleteUser=track(`deleteUser`,t.deleteUser,e.namespace),this.sendPasswordResetEmail=track(`sendPasswordResetEmail`,t.sendPasswordResetEmail,e.namespace),this.unenrollMfa=track(`unenrollMfa`,t.unenrollMfa,e.namespace)},s=I.fn(defaultClient);t.idp={Client:s};function allMocks(){return[...o.values()].flatMap(e=>G.map(t=>e[t]))}return f({Client:s,namespace,setResolver(e){resolver=e},enqueueResult(e){i.push(e)},enqueueResults(...e){i.push(...e)},get calls(){return a},clear(){a.length=0,s.mockClear();for(let e of allMocks())e.mockClear()},reset(){i.length=0,a.length=0,resolver=()=>null,s.mockReset(),s.mockImplementation(defaultClient);for(let e of allMocks())e.mockReset()}},()=>{t.idp=n})}function mockLogger(e={}){let t=p(),n=t.logger,r=I.fn((e,t)=>{}),i=I.fn((e,t)=>{}),a=I.fn((e,t)=>{}),o=I.fn((e,t)=>{}),s=I.fn(e=>{});t.logger={debug:r,info:i,warn:a,error:o,setAttributes:s};let c={debug:r,info:i,warn:a,error:o};return f({debug:r,info:i,warn:a,error:o,setAttributes:s,get calls(){return Object.entries(c).flatMap(([e,t])=>t.mock.calls.map((n,r)=>({order:t.mock.invocationCallOrder[r]??0,call:{severity:e,message:n[0],attributes:n[1]}}))).toSorted((e,t)=>e.order-t.order).map(e=>e.call)},clear(){r.mockClear(),i.mockClear(),a.mockClear(),o.mockClear(),s.mockClear()},reset(){r.mockReset(),i.mockReset(),a.mockReset(),o.mockReset(),s.mockReset()}},()=>{t.logger=n})}function testRegex(e,t){let n=e.lastIndex;e.lastIndex=0;try{return e.test(t)}finally{e.lastIndex=n}}var MockQueryResult=class{command;rowCount;rows;constructor(e){this.command=``,this.rowCount=e.length,this.rows=e}};function mockTailordb(e={}){let t=m(),n=t.Client,r=[],i;function matchesQuery(e,t,n){if(typeof e==`function`)return e(t,n);if(typeof e==`string`)return t===e;if(e instanceof RegExp)return testRegex(e,t);let r;if(r=typeof e.sql==`string`?t===e.sql:testRegex(e.sql,t),!r||e.params===void 0)return r;if(typeof e.params==`function`)return e.params(n);let i=e.params;return n.length===i.length&&n.every((e,t)=>g(e,i[t]))}function queryResponse(e){if(e.type===`error`)throw e.error;return new MockQueryResult(e.rows)}async function defaultQuery(t,n=[]){for(let e=r.length-1;e>=0;--e){let i=r[e];if(!i||!matchesQuery(i.matcher,t,n))continue;let a=i.once.shift();if(a)return queryResponse(a);if(i.fallback)return queryResponse(i.fallback)}if(i)return new MockQueryResult(i(t,n)??[]);if(e.onUnhandled===`error`)throw Error(`No TailorDB query behavior matched: ${t}`);return new MockQueryResult([])}let a=I.fn(defaultQuery),defaultConnect=async()=>{},o=I.fn(defaultConnect),s=[];function enqueueRowsList(e){for(let t of e)a.mockImplementationOnce(async()=>new MockQueryResult(t))}let defaultClient=function(e){let t={namespace:e?.namespace,ended:!1};s.push(t),this.connect=o,this.end=I.fn(async()=>{t.ended=!0}),this.queryObject=a,this.createTransaction=e=>{if(!e)throw Error(`Transaction name must be a non-empty string`);return{begin:async()=>{},commit:async()=>{},rollback:async()=>{},queryObject:a}}},c=I.fn(defaultClient);return t.Client=c,f({Client:c,queryObject:a,setQueryResolver(e){i=e,a.mockImplementation(defaultQuery)},onQuery(e){let t={matcher:e,once:[]};r.push(t);let n={returnsRows(e){return t.fallback={type:`rows`,rows:e},n},returnsRowsOnce(e){return t.once.push({type:`rows`,rows:e}),n},rejects(e){return t.fallback={type:`error`,error:e},n},rejectsOnce(e){return t.once.push({type:`error`,error:e}),n}};return n},enqueueResult(...e){enqueueRowsList([e])},enqueueResults(...e){enqueueRowsList(e)},enqueueRows(...e){enqueueRowsList(e)},get executedQueries(){return a.mock.calls.map(([e,t])=>({query:e,params:t??[]}))},get createdClients(){return s},clear(){a.mockClear(),o.mockClear(),c.mockClear(),s.length=0},reset(){a.mockReset(),a.mockImplementation(defaultQuery),o.mockReset(),o.mockImplementation(defaultConnect),c.mockReset(),c.mockImplementation(defaultClient),s.length=0,r.length=0,i=void 0}},()=>{t.Client=n})}const J=new WeakMap,Y=new WeakMap,X=new WeakMap;function replaceProcedure(e,t,n){let r=X.get(n)??n,i=I.fn(function(...e){return Reflect.apply(r,this,e)});X.set(i,r);let a=e;return a[t]=i,{mock:i,scoped:{mockClear:()=>i.mockClear(),mockReset:()=>i.mockReset(),restore:()=>{a[t]===i&&(a[t]=n)}}}}function replaceStart(e){return replaceProcedure(e,`start`,e.start)}function mockWorkflow(){let e=p(),a=e.workflow,c=r(),l=new Map,u=new Map,m=new Map,h=new Map,g=new Set,installKeyDispatcher=e=>{let t=h.get(e);if(t)return t;let n=i(e);if(!n)throw Error(`waitPointWith expects a wait point definition created by createWaitPoint or createWaitPoints.`);let r=n,a=n.wait,o=n.resolve,s=J.get(a)??a,c=Y.get(o)??o,l={perKey:new Map,originalWait:(e,t)=>s.call(n,e,t),originalResolve:(e,t,r)=>c.call(n,e,t,r)},dispatchWait=(e,t)=>{let n=l.perKey.get(e);return n?t===void 0?n.wait():n.wait(t):l.originalWait(e,t)},dispatchResolve=async(e,t,n)=>{let r=l.perKey.get(e);if(!r)return l.originalResolve(e,t,n);await r.resolve(t,n)};J.set(dispatchWait,s),Y.set(dispatchResolve,c),r.wait=dispatchWait,r.resolve=dispatchResolve;let eachSpy=e=>{for(let t of l.perKey.values()){let n=t;e(n.wait),e(n.resolve)}};return g.add({mockClear:()=>eachSpy(e=>e.mockClear()),mockReset:()=>eachSpy(e=>e.mockReset()),restore:()=>{r.wait=a,r.resolve=o,h.delete(e)}}),h.set(e,l),l},defaultExecJob=(e,t,n)=>{throw Error(`No workflow job mock for "${e}". Call mockWorkflow().setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`)},defaultStartWorkflow=async(e,n,r)=>t,defaultResumeWorkflowExecution=async e=>e,_=I.fn(defaultExecJob),v=I.fn(defaultStartWorkflow),y=I.fn(defaultResumeWorkflowExecution),b=I.fn((e,t)=>null),x=I.fn(async(e,t,n)=>{});return e.workflow={execJobFunction:(...e)=>{let t=e.length>=3?_(e[0],d(e[1]),e[2]):_(e[0],d(e[1]));return t instanceof Promise?t.then(e=>d(e)):d(t)},startWorkflow:(...e)=>e.length>=3?v(e[0],d(e[1]),e[2]):v(e[0],d(e[1])),resumeWorkflowExecution:e=>y(e),wait:(e,t)=>b(e,d(t)),resolve:(e,t,n)=>x(e,t,e=>{let t=n(e);return t instanceof Promise?t.then(e=>d(e)):d(t)})},f({execJobFunction:_,startWorkflow:v,resumeWorkflowExecution:y,wait:b,resolve:x,job(e){let t=l.get(e);if(t)return t;let{mock:n,scoped:r}=replaceStart(e);return g.add(r),l.set(e,n),n},workflow(e){let t=u.get(e);if(t)return t;let{mock:n,scoped:r}=replaceStart(e);return u.set(e,n),g.add(r),n},waitPoint(e){let t=m.get(e);if(t)return t;let n=replaceProcedure(e,`wait`,e.wait),r=replaceProcedure(e,`resolve`,e.resolve),i=n.mock,a=r.mock;g.add(n.scoped),g.add(r.scoped);let o={wait:i,resolve:a,setResolvePayload(e){a.mockImplementation(async(t,n)=>{let r=await n(d(e));d(r)})}};return m.set(e,o),o},waitPointWith(e,t){let r=n(e.with(t));if(r===void 0)throw Error(`waitPointWith expects a wait point declared with $params. Use waitPoint() for a wait point with a fixed key.`);let i=installKeyDispatcher(e),a=i.perKey.get(r);if(a)return a;let o=I.fn(e=>Promise.resolve(i.originalWait(r,e))),s=I.fn((e,t)=>i.originalResolve(r,e,t)),c={wait:o,resolve:s,setResolvePayload(e){s.mockImplementation(async(t,n)=>{let r=await n(d(e));d(r)})}};return i.perKey.set(r,c),c},setJobHandler(e){_.mockImplementation((t,n,r)=>e(t,n,r))},enqueueResult(e){_.mockImplementationOnce(()=>e)},enqueueResults(...e){for(let t of e)_.mockImplementationOnce(()=>t)},get startedJobs(){return _.mock.calls.map(([e,t,n])=>({jobName:e,args:t,...n!==void 0&&{options:n}}))},setStartHandler(e){v.mockImplementation(typeof e==`function`?async(t,n,r)=>e(t,n,r):async()=>e)},setResumeHandler(e){y.mockImplementation(typeof e==`function`?async t=>e(t):async()=>e)},setWaitHandler:e=>{b.mockImplementation(typeof e==`function`?(t,n)=>e(t,n):()=>e)},setEnv(e){s({...e})},setResolveHandler(e){x.mockImplementation(async(t,n,r)=>{await e(t,n,r)})},get waitCalls(){return b.mock.calls.map(([e,t])=>({key:e,payload:t}))},get resolveCalls(){return x.mock.calls.map(([e,t])=>({executionId:e,key:t}))},clear(){_.mockClear(),v.mockClear(),y.mockClear(),b.mockClear(),x.mockClear();for(let e of g)e.mockClear()},reset(){_.mockReset(),_.mockImplementation(defaultExecJob),v.mockReset(),v.mockImplementation(defaultStartWorkflow),y.mockReset(),y.mockImplementation(defaultResumeWorkflowExecution),b.mockReset(),b.mockImplementation(()=>null),x.mockReset(),x.mockImplementation(async()=>{});for(let e of g)e.mockReset();o()}},()=>{for(let e of g)e.restore();e.workflow=a,c===void 0?o():s(c)})}var PendingStart=class{jobName;args;constructor(e,t){this.jobName=e,this.args=t}};async function runWorkflowLocally(e,t,n){let i=globalThis,a=i.tailor,c=r(),l=c!==void 0,u=createLocalJobRunner();n?.env!==void 0&&s({...n.env}),i.tailor={...a,workflow:createLocalWorkflowRuntime(a?.workflow,u.execJobFunction)};try{return await u.runJob(e.mainJob.name,t)}finally{a?i.tailor=a:delete i.tailor,n?.env!==void 0&&(l?s(c):o())}}function createLocalJobRunner(){let t,execJobFunction=(e,n)=>{if(!t)throw Error(`Cannot start workflow job "${e}" outside runWorkflowLocally() job execution.`);if(t.pending)throw t.pending;let r=d(n),i=t.cursor;t.cursor+=1;let a=t.records[i];if(a){if(assertSameStart(a,e,r),a.status===`rejected`)throw a.error;return d(a.result)}let o=new PendingStart(e,r);throw t.pending=o,o},runJob=async(n,r)=>{let i=e(n);if(!i)return null;let o=[];for(;;){let e={records:o,cursor:0},s=t;t=e;try{let t=await i(d(r),a());if(e.pending){await settlePendingStart(o,e.pending,runJob);continue}if(e.cursor!==o.length)throw Error(`Workflow job start sequence changed while replaying "${n}". Expected ${o.length} start(s), but replay reached ${e.cursor}.`);return d(t)}catch(t){let n=t instanceof PendingStart?t:e.pending;if(n){await settlePendingStart(o,n,runJob);continue}throw t}finally{t=s}}};return{runJob,execJobFunction}}async function settlePendingStart(e,t,n){try{e.push({jobName:t.jobName,args:t.args,status:`fulfilled`,result:await n(t.jobName,t.args)})}catch(n){e.push({jobName:t.jobName,args:t.args,status:`rejected`,error:n})}}function assertSameStart(e,t,n){if(e.jobName!==t||JSON.stringify(e.args)!==JSON.stringify(n))throw Error(`Workflow job start sequence changed while replaying. Expected ${e.jobName}(${JSON.stringify(e.args)}), but got ${t}(${JSON.stringify(n)}).`)}function createLocalWorkflowRuntime(e,n){return{execJobFunction:n,startWorkflow:async(n,r,i)=>e?await e.startWorkflow(n,r,i):(d(r),t),resumeWorkflowExecution:async t=>e?await e.resumeWorkflowExecution(t):t,wait:(t,n)=>{if(e)return e.wait(t,n);throw Error(`No wait handler for "${t}". Acquire mockWorkflow() and call setWaitHandler(...).`)},resolve:async(t,n,r)=>{if(e){await e.resolve(t,n,r);return}throw Error(`No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).`)}}}function unwrapValue(e){return k.is(e)?e.value:e}function insertRows(e){if(!b.is(e))throw Error(`insertRows: expected InsertQueryNode, got ${e.kind}`);let t=e.columns,n=e.values;if(t===void 0||n===void 0||!A.is(n))throw Error(`insertRows: unsupported insert shape; inspect query.node instead`);return n.values.map(e=>{if(!T.is(e)&&!O.is(e))throw Error(`insertRows: unsupported insert shape; inspect query.node instead`);let n=T.is(e)?e.values:e.values.map(unwrapValue),r={};return t.forEach((e,t)=>{r[e.column.name]=n[t]}),r})}function insertValues(e){let t=insertRows(e);if(t.length!==1)throw Error(`insertValues: query inserts ${t.length} rows; use insertRows() for multi-row inserts`);return c(t[0],`insertValues: first row missing`)}function updateValues(e){if(!D.is(e))throw Error(`updateValues: expected UpdateQueryNode, got ${e.kind}`);if(e.updates===void 0)throw Error(`updateValues: unsupported update shape; inspect query.node instead`);let t={};for(let n of e.updates){let e=n.column,r=v.is(e)?e.column.name:E.is(e)&&v.is(e.column)?e.column.column.name:void 0;if(r===void 0)throw Error(`updateValues: unsupported update shape; inspect query.node instead`);t[r]=unwrapValue(n.value)}return t}function toExecutedQuery(e){let t=e.query;return{kind:t.kind,sql:e.sql,parameters:e.parameters,node:t,insertRows:()=>insertRows(t),insertValues:()=>insertValues(t),updateValues:()=>updateValues(t)}}function toStagedResult(e){return Array.isArray(e)?{rows:e,numAffectedRows:void 0}:{rows:e.rows??[],numAffectedRows:e.numAffectedRows===void 0?void 0:BigInt(e.numAffectedRows)}}var MockState=class{executed=[];queue=[];resolver;enqueue(...e){this.queue.push(...e)}setResolver(e){this.resolver=e}next(e){let t=this.resolver?.(e);if(t!==void 0)return toStagedResult(t);let n=this.queue.shift();return n===void 0?{rows:[],numAffectedRows:void 0}:toStagedResult(n)}reset(){this.executed.length=0,this.queue.length=0,this.resolver=void 0}},MockConnection=class{state;constructor(e){this.state=e}async executeQuery(e){let t=toExecutedQuery(e);this.state.executed.push(t);let{rows:n,numAffectedRows:r}=this.state.next(t);return{rows:n,numAffectedRows:r??BigInt(n.length)}}streamQuery(){throw Error(`createKyselyMock: streaming is not supported`)}},MockDriver=class{state;constructor(e){this.state=e}async init(){}async acquireConnection(){return new MockConnection(this.state)}async beginTransaction(){}async commitTransaction(){}async rollbackTransaction(){}async releaseConnection(){}async destroy(){}};function byKind(e,t){return e.executed.filter(e=>e.kind===t)}function createKyselyMock(){let e=new MockState,t=new x({dialect:{createDriver:()=>new MockDriver(e),createQueryCompiler:()=>new w,createAdapter:()=>new S,createIntrospector:e=>new C(e)}});return{db:t,get executedQueries(){return e.executed},get selects(){return byKind(e,`SelectQueryNode`)},get inserts(){return byKind(e,`InsertQueryNode`)},get updates(){return byKind(e,`UpdateQueryNode`)},get deletes(){return byKind(e,`DeleteQueryNode`)},enqueueResult:t=>e.enqueue(t),enqueueResults:(...t)=>e.enqueue(...t),setQueryResolver:t=>e.setResolver(t),withTx:e=>t.transaction().execute(e),reset:()=>e.reset(),[Symbol.dispose]:()=>e.reset()}}var PGliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let t=await this.#e.query(e.sql,[...e.parameters]);return{rows:t.rows,numAffectedRows:BigInt(t.affectedRows??0)}}streamQuery(){throw Error(`createKyselyPGlite: streaming is not supported`)}},PGliteDriver=class{#e;constructor(e){this.#e=e}async init(){}async acquireConnection(){return new PGliteConnection(this.#e)}async beginTransaction(e,t){let n=t.isolationLevel?[`start transaction`,`isolation level ${t.isolationLevel}`]:[`begin`];t.accessMode&&n.push(t.accessMode),await e.executeQuery(y.raw(n.join(` `)))}async commitTransaction(e){await e.executeQuery(y.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(y.raw(`rollback`))}async releaseConnection(){}async destroy(){await this.#e.close()}};function createKyselyPGlite(e){return new x({dialect:{createAdapter:()=>new S,createDriver:()=>new PGliteDriver(e),createIntrospector:e=>new C(e),createQueryCompiler:()=>new w}})}function tailorRuntime(e){return[createBlockPlugin(),createEnvironmentPlugin(e)]}export{createKyselyMock,createKyselyPGlite,mockAigateway,mockAuthconnection,mockFile,mockIconv,mockIdp,mockLogger,h as mockSecretmanager,mockTailordb,mockWorkflow,runWorkflowLocally,tailorRuntime};
|
|
1981
2
|
//# sourceMappingURL=index.mjs.map
|