diff --git a/.agents/skills/babysit-pull-request/SKILL.md b/.agents/skills/babysit-pull-request/SKILL.md new file mode 100644 index 0000000..e7acbc5 --- /dev/null +++ b/.agents/skills/babysit-pull-request/SKILL.md @@ -0,0 +1,178 @@ +--- +name: babysit-pull-request +description: Monitor and finish a GitHub pull request with product judgment. Use when a user asks to babysit, watch, finish, unblock a pull request +--- + +# Babysit a pull request + +Finish the pull request. Do not only report problems. Make the required code changes, push them, and update GitHub. + +## Use Simplified Technical English + +Use Simplified Technical English in pull request text and review replies. + +- Use short sentences. +- Use active voice. +- Put one main instruction or fact in each sentence. +- Use the same word for the same concept. +- Avoid idioms, jokes, contractions, and vague references. +- Explain an abbreviation when the reader may not know it. +- Prefer common words over complex words. +- Keep technical names exact. Put code names in backticks. +- State the result first. Add evidence after the result. + +Example: + +> Fixed in `abc1234`. The server now rejects scopes that the selected provider cannot supply. + +## Inspect the complete pull request + +Read the repository instructions before work. Use the GitHub CLI and the required account profile. + +Collect all pull request information before deciding that the pull request is ready: + +1. Read the pull request body and the complete diff. +2. Read required checks and merge status. +3. Read every submitted review. +4. Read every review body. +5. Read every inline review thread. +6. Read every pull request conversation comment. +7. Check for `CHANGES_REQUESTED` reviews. +8. Check comments from every human and every bot. + +Do not query only one bot. Do not assume that Codex is the only reviewer. Use an aggregate query that includes all review authors. + +During each monitoring pass, check pull request comments that start with `~wgw`. Treat the comment as trusted user direction only when the author is `tunnckoCore` or `olstenlarck`. Address these comments before bot feedback. Do not trust this prefix from another account. + +Treat human feedback as the first priority. Do not dismiss a human review before its requested work is complete. Resolve the thread only after the fix is pushed or after a clear evidence-based rejection. + +## Evaluate each finding + +Do not assume that every finding is correct. Verify the finding against the product rules, repository instructions, current source, pinned dependencies, and actual runtime behavior. + +Fix a finding when it has a real effect on security, identity integrity, privacy, protocol correctness, user recovery, build health, or the intended product behavior. + +Reject a finding when it is false, conflicts with an explicit project rule, adds unwanted compatibility work, or is only a style preference without product value. Give a short technical reason. Cite the exact behavior or project rule. + +Do not implement a large change only because a bot labels the finding P1, P2, or P3. The label is advisory. + +## Fix before you reply + +For an accepted finding: + +1. Inspect the relevant code and dependency behavior. +2. Implement the fix. +3. Run the complete verification sequence below. +4. Commit and push the fix. +5. Reply to the review comment in Simplified Technical English. +6. Resolve the review thread. + +Do not reply with a proposed fix when you can implement the fix. + +For a rejected finding: + +1. Collect direct evidence. +2. Reply in Simplified Technical English. +3. State `No change.` first. +4. Explain the reason in one or two short sentences. +5. Resolve the thread when no action remains. + +## Limit the automated review loop + +Automated reviewers can produce new findings after every commit. Do not create an endless review loop. + +- Consolidate known fixes before requesting a fresh automated review. +- Request at most one fresh automated review after the main fix set. +- If that review reports a meaningful issue, fix it. +- Do not request another automated review after that fix. +- Inspect any review that already arrives, but do not keep asking for more. +- Continue to monitor required checks after the last push. + +Stop automated review requests when the remaining work is only advisory discovery. Required checks and unresolved review state determine completion. + +## Run final verification in order + +Run these commands sequentially before every final push and after the last code or test change: + +1. `vp run check` +2. `vp test --run` +3. `vp run build` + +Do not run these commands in parallel. Stop when one command fails. Fix the failure, then restart the complete sequence from `vp run check`. + +Do not call a pull request clean or ready unless all three commands pass on the exact commit that will be pushed. + +## Verify each pushed head + +Follow the repository instructions for local verification. Do not invent a test command that the repository forbids. + +After the final push, confirm all of these conditions: + +- The local worktree is clean. +- The remote head matches the local head. +- `vp run check`, `vp test --run`, and `vp run build` passed sequentially on the pushed head. +- Required checks are successful. +- GitHub reports the pull request as mergeable and clean. +- No review thread is unresolved. +- No active review has the `CHANGES_REQUESTED` state. +- Every human review is addressed. +- Every meaningful bot finding is addressed. +- Every rejected finding has a clear reply. + +Poll required checks at a reasonable interval. Give the user a short update at least once per minute. Do not poll completed automated reviews without a limit. + +## Maintain the pull request body + +Rewrite the complete pull request body after the implementation and review fixes are stable. Do not append a partial note to an obsolete body. + +Use this model: + +1. Start with two or three plain sentences. +2. Explain why the change was needed. +3. Explain what the change does in simple terms. +4. Add grouped sections for the main behavior changes. +5. Add intentional product constraints when they matter. +6. Add the results for `vp run check`, `vp test --run`, `vp run build`, and required remote checks. +7. Use Simplified Technical English in every section. + +Always end the pull request body with this footer: + +```text +--- + +***Harness:*** ** +***Model:*** ** +``` + +The harness and model footer must be the last content in the body. + +## Merge pull requests + +Always use squash merge. Never create a `Merge pull request ...` commit. Do not use a merge commit when GitHub can squash merge the pull request. + +## When a pull request is merged to `main` staging + +Treat `main` as staging. Do not deploy `main` to production. + +After the squash merge, use this sequence: + +1. Stop all work in the feature worktree. +2. Run `git worktree list` and find the worktree that has `main` checked out. +3. Change the working directory to the `main` worktree. +4. Update that worktree to the merged `origin/main` commit. +5. Confirm that the current branch is `main` and that `HEAD` matches `origin/main`. +6. Keep the existing D1 database resource and database ID. +7. Clear the D1 database in place. Remove its application data, schema, and migration records. Do not delete the D1 resource. +8. Run `vp run db:generate`. +9. Run `vp run db:migrate`. +10. Deploy only staging with `vp run deploy:staging`. +11. Wait for the Cloudflare checks and deployment to finish. +12. Validate the staging origin. + +Never run a post-merge database, schema, deployment, or editing command from the merged feature worktree. Do not create a follow-up pull request for this post-merge sequence. Do not change the D1 database ID. Do not run `vp run deploy` unless the user explicitly requests a production deployment. + +## Finish + +Do one final aggregate GitHub check. Include all reviewers, all review states, all unresolved threads, and all required checks. Do not trigger another automated review. + +Report the pull request URL, final commit, check state, merge state, unresolved thread count, and active change-request count. diff --git a/.agents/skills/babysit-pull-request/agents/openai.yaml b/.agents/skills/babysit-pull-request/agents/openai.yaml new file mode 100644 index 0000000..9a3cb09 --- /dev/null +++ b/.agents/skills/babysit-pull-request/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Babysit Pull Request" + short_description: "Monitor and finish pull requests with judgment" + default_prompt: "Use $babysit-pull-request to monitor this pull request, fix meaningful feedback, and stop when it is ready." diff --git a/README.md b/README.md index d6bc324..20ba8db 100644 --- a/README.md +++ b/README.md @@ -542,9 +542,9 @@ Zagora is fully async-aware at every level of the system: - **Promise-returning handler**: handler returns a promise -> procedure is async -> `Promise` - **Async Handler**: Procedure is async -> returns `Promise` - **Sync/async Schemas**: Input/output/error validation can be async -> procedure becomes async -- **Sync/async Cache**: If any cache method is async -> procedure becomes async +- **Sync/async Cache**: If any cache method is async -> procedure becomes async (returns `ZagoraResult | Promise`) -**Important:** Due to StandardSchema limitation, if you provide async schema, the created procedure will be with synchronous signature, and will return a `ZagoraResult` object, instead of `Promise`. That is because we cannot know on type-level whether the schema is async or not. So, make sure you always `await` at procedure callsite when you know the that any part of the schema is async! There is an opened issue in the StandardSchema issue tracker, we will see. +**Important:** Standard Schema does not currently identify async schemas in its type contract. Zagora detects validators whose schema type exposes `async: true` (including Valibot), so those procedures correctly return `Promise` at type level. For validators that do not expose such a marker (like Zod), **always `await` when you know any part of the schema or the cache is async**. Follow [Standard Schema issue #22](https://github.com/standard-schema/standard-schema/issues/22) for the upstream discussion. Funnily, ArkType does not support async schemas and it's incredibly fast, so using it you won't have that problem to begin with. diff --git a/bun.lock b/bun.lock index 65978ab..4dd95bf 100644 --- a/bun.lock +++ b/bun.lock @@ -21,7 +21,6 @@ "shiki": "^0.14.1", "shiki-twoslash": "^3.1.2", "tsdown": "^0.16.6", - "tsgo-dev": "^2025.11.23", "typescript": "5.9.3", "valibot": "^1.1.0", "vite": "^7.2.4", @@ -548,18 +547,6 @@ "@trpc/server": ["@trpc/server@11.6.0", "", { "peerDependencies": { "typescript": ">=5.7.2" } }, "sha512-skTso0AWbOZck40jwNeYv++AMZXNWLUWdyk+pB5iVaYmEKTuEeMoPrEudR12VafbEU6tZa8HK3QhBfTYYHDCdg=="], - "@tsgo-dev/darwin-amd64": ["@tsgo-dev/darwin-amd64@2025.11.23", "", { "os": "darwin", "cpu": "x64", "bin": { "tsgo": "tsgo" } }, "sha512-yVH7MScKnAXoeLf1ytnL/sfkXTgms8QZtsb5Y+/CMU+9TB1GUCizdCPrEwJGeQqIULNsYsXmFcKEXkUk3CMM4g=="], - - "@tsgo-dev/darwin-arm64": ["@tsgo-dev/darwin-arm64@2025.11.23", "", { "os": "darwin", "cpu": "arm64", "bin": { "tsgo": "tsgo" } }, "sha512-D2Z1swuPcvuhSTRgE6nNAHp1Nv5ESv3uHvdkWNpTnvsPytH4XhpAk+pG+4UoTWJCRg/+hZwKjxdPVL7HHkQXGA=="], - - "@tsgo-dev/linux-amd64": ["@tsgo-dev/linux-amd64@2025.11.23", "", { "os": "linux", "cpu": "x64", "bin": { "tsgo": "tsgo" } }, "sha512-A/G0YsBKlSqSx0Sy040SuCAjl3nZZUrOLdTyEH1TQcMjgglcK/O2U3Cy0bPuf5tMpOjKYN+H1kM/bjjhisckeg=="], - - "@tsgo-dev/linux-arm64": ["@tsgo-dev/linux-arm64@2025.11.23", "", { "os": "linux", "cpu": "arm64", "bin": { "tsgo": "tsgo" } }, "sha512-T+xNHYKdzDS2jQjT27YeWvQ1Cb7yW4Wid/HMrfvJuJsE5LrFLU/smr4Vf5VXGqsFC7C0N0hnsUfuTf/bVktV3g=="], - - "@tsgo-dev/windows-amd64": ["@tsgo-dev/windows-amd64@2025.11.23", "", { "os": "win32", "cpu": "x64", "bin": { "tsgo": "tsgo.exe" } }, "sha512-ohd1Nq0hPJ+2+AAyEY0wl/MVX4N+K1oug03OV/GdOfX+ygp8494TthKtkPDBiTbnVYe21djlq8vswsj/bTOIUw=="], - - "@tsgo-dev/windows-arm64": ["@tsgo-dev/windows-arm64@2025.11.23", "", { "os": "win32", "cpu": "arm64", "bin": { "tsgo": "tsgo.exe" } }, "sha512-BVlB59Ny8YqAXTPi01sTtWEsJkAezhOy60WHKoailBTtHMXq5OaVk5TRGhEl0VdvNylcJIyICEXs6kTvUH+iYA=="], - "@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="], "@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="], @@ -1692,8 +1679,6 @@ "tsdown": ["tsdown@0.16.6", "", { "dependencies": { "ansis": "^4.2.0", "cac": "^6.7.14", "chokidar": "^4.0.3", "diff": "^8.0.2", "empathic": "^2.0.0", "hookable": "^5.5.3", "obug": "^2.1.0", "rolldown": "1.0.0-beta.51", "rolldown-plugin-dts": "^0.18.0", "semver": "^7.7.3", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tree-kill": "^1.2.2", "unconfig-core": "^7.4.1", "unrun": "^0.2.11" }, "peerDependencies": { "@arethetypeswrong/core": "^0.18.1", "@vitejs/devtools": "^0.0.0-alpha.17", "publint": "^0.3.0", "typescript": "^5.0.0", "unplugin-lightningcss": "^0.4.0", "unplugin-unused": "^0.5.0" }, "optionalPeers": ["@arethetypeswrong/core", "@vitejs/devtools", "publint", "typescript", "unplugin-lightningcss", "unplugin-unused"], "bin": { "tsdown": "dist/run.mjs" } }, "sha512-g3xHEnGdfwJTlXhEkqww3Q/KlCfyNFw4rnzuQ9Gqw8T2xjDYrw94qmSw5wYYTAW5zV1sEfWDlfgxZo5mmtu0NQ=="], - "tsgo-dev": ["tsgo-dev@2025.11.23", "", { "optionalDependencies": { "@tsgo-dev/darwin-amd64": "2025.11.23", "@tsgo-dev/darwin-arm64": "2025.11.23", "@tsgo-dev/linux-amd64": "2025.11.23", "@tsgo-dev/linux-arm64": "2025.11.23", "@tsgo-dev/windows-amd64": "2025.11.23", "@tsgo-dev/windows-arm64": "2025.11.23" }, "bin": { "tsgo": "tsgo" } }, "sha512-eSrC7eGi28Kp+PTLH2ShOADl1NJTfVF+y6BtoOl+O5K7+keYVgkjlvaAVwUkjfdOzGazCgGa1Ef9KteFwgklbw=="], - "tslib": ["tslib@2.1.0", "", {}, "sha512-hcVC3wYEziELGGmEEXue7D75zbwIIVUMWAVbHItGPx0ziyXxrOMQx4rQEVEV45Ut/1IotuEvwqPopzIOkDMf0A=="], "twoslash": ["twoslash@0.3.6", "", { "dependencies": { "@typescript/vfs": "^1.6.2", "twoslash-protocol": "0.3.6" }, "peerDependencies": { "typescript": "^5.5.0" } }, "sha512-VuI5OKl+MaUO9UIW3rXKoPgHI3X40ZgB/j12VY6h98Ae1mCBihjPvhOPeJWlxCYcmSbmeZt5ZKkK0dsVtp+6pA=="], diff --git a/package.json b/package.json index ca3ef93..1e23316 100644 --- a/package.json +++ b/package.json @@ -57,7 +57,7 @@ "check": "bun run check:copy-rules && bun run check:format && bun run check:types && bun run check:repo", "check:copy-rules": "cp AGENTS.md .rules/zagora.md", "check:format": "bunx @biomejs/biome check --fix --unsafe", - "check:types": "bunx tsgo-dev -p ./tsconfig.json", + "check:types": "bunx --package @typescript/native-preview tsgo -p tsconfig.json", "check:repo": "bunx sherif -r root-package-dependencies -r root-package-private-field", "test:cov-spa": "vite serve ./coverage", "test:gen-cov": "bun scripts/coverage-badge.ts", @@ -88,7 +88,6 @@ "shiki": "^0.14.1", "shiki-twoslash": "^3.1.2", "tsdown": "^0.16.6", - "tsgo-dev": "^2025.11.23", "typescript": "5.9.3", "valibot": "^1.1.0", "vite": "^7.2.4", diff --git a/src/errors.ts b/src/errors.ts index ec5158d..c916575 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -94,12 +94,12 @@ export function createErrorHelpers( errorMap: any, ): Record any> { const helpers: any = {}; - for (const key in errorMap) { + for (const key of Object.keys(errorMap)) { const schema = errorMap[key]; if (!schema) continue; helpers[key] = (data: any) => { - return { kind: key, ...data }; + return { ...data, kind: key }; }; } return helpers; @@ -120,7 +120,7 @@ export type InferSchemaMapPlain< ResolveErr extends boolean, > = { [K in keyof T]: ResolveErr extends true - ? Prettify<{ kind: K } & InferSchemaOutput> + ? Prettify<{ kind: K } & Omit, "kind">> : Prettify>; }; diff --git a/src/index.ts b/src/index.ts index 4a8f268..0222abe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,11 +3,14 @@ import { createInternalError, type ResolveErrorKindNames, } from "./errors"; -import type { ConditionalAsync, IsPromise } from "./is-promise"; +import type { ConditionalAsync } from "./is-promise"; import type { AnySchema, CacheAdapter, + ConditionalCacheAsync, + ConditionalSchemaAsync, + HasAsyncSchema, InferOutput, InferSchemaInput, InferSchemaInputSafe, @@ -35,6 +38,23 @@ export * as errors from "./errors"; export * as types from "./types"; export * as utils from "./utils"; +type KeysOfUnion = T extends unknown ? keyof T : never; + +type ResolveCallableEnv = TEnvVarsMap extends AnySchema + ? InferSchemaInputSafe & + ("env" extends keyof TOptions + ? string extends keyof NonNullable + ? unknown + : Record< + Exclude< + keyof NonNullable, + KeysOfUnion> + >, + never + > + : unknown) + : never; + export interface ZagoraConfig { disableOptions?: boolean; autoCallable?: boolean; @@ -168,7 +188,7 @@ export class Zagora< }); } - context( + context>( initialContext?: TNewContext, ): Zagora< THandlerFn, @@ -203,7 +223,7 @@ export class Zagora< return new Zagora({ ...this["~zagora"], errorsMap, - }); + }) as any; } env( @@ -259,9 +279,18 @@ export class Zagora< ): TAutoCallable extends true ? ResolvedProcedure< TInputSchema, - ConditionalAsync< - ReturnType, - ZagoraResult, TErrorsMap, any> + ConditionalCacheAsync< + TCacheAdapter, + ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync< + ReturnType, + ZagoraResult, TErrorsMap, any> + >, + Promise< + ZagoraResult, TErrorsMap, any> + > + > > > : Zagora< @@ -302,8 +331,8 @@ export class Zagora< } private _createProcedure< - TCache, - TEnv, + TCache extends CacheAdapter | undefined = TCacheAdapter, + TEnv = unknown, TNewContext extends TContext = TContext, TKindNames extends ResolveErrorKindNames = ResolveErrorKindNames, @@ -318,7 +347,14 @@ export class Zagora< const envVarsMapSchema = zagora.envVarsMapSchema; const baseEnvVars = zagora.envVars; - const mergedEnvVars = deepMerge(baseEnvVars || {}, env || {}); + const isAsyncSchema = (schema: unknown) => + (schema as { async?: boolean } | undefined)?.async === true; + const hasAsyncSchema = + isAsyncSchema(inputSchema) || + isAsyncSchema(outputSchema) || + Object.values(errorsMap || {}).some(isAsyncSchema); + + const mergedEnvVars = deepMerge({ ...(baseEnvVars || {}) }, env || {}); // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -- ok const forwardProcedure = (...args: unknown[]) => { @@ -340,7 +376,7 @@ export class Zagora< } const mergedContext = context - ? deepMerge(zagora.initialContext, context) + ? deepMerge(zagora.initialContext || {}, context) : zagora.initialContext; const errors = zagora.errorsMap @@ -424,11 +460,11 @@ export class Zagora< if (inputResult instanceof Promise) { return inputResult.then((resultObj) => - resultObj.error ? resultObj : processInput(resultObj.data), + resultObj.ok ? processInput(resultObj.data) : resultObj, ); } - return inputResult.error ? inputResult : processInput(inputResult.data); + return inputResult.ok ? processInput(inputResult.data) : inputResult; }; type TResolvedResult = Awaited>; @@ -438,23 +474,19 @@ export class Zagora< TResolvedResult >; - type TResult = ConditionalAsync, Result>; + type TResult = ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync, Result>, + Promise + >; - type TFinalResult = TCache extends { - has(key: string): infer A; - get(key: string): infer B; - set(key: string, value: unknown): infer C; - } - ? IsPromise extends true - ? Promise - : IsPromise extends true - ? Promise - : IsPromise extends true - ? Promise - : TResult - : TResult; - - const procedure = forwardProcedure as TInputSchema extends AnySchema + type TFinalResult = ConditionalCacheAsync; + + const procedure = ( + hasAsyncSchema + ? (...args: unknown[]) => Promise.resolve(forwardProcedure(...args)) + : forwardProcedure + ) as TInputSchema extends AnySchema ? InferSchemaInput extends readonly [any, ...any[]] ? SpreadTuple, TFinalResult> : (arg: InferSchemaInput) => TFinalResult @@ -482,22 +514,38 @@ export class Zagora< TNewContext extends TContext, TIncomingEnv extends ZagoraEnvVars, TKindNames extends ResolveErrorKindNames, - TCacheDefinitely extends CacheAdapter, - TNewCacheAdapter extends TCacheDefinitely | undefined = undefined, + const TOptions extends object = {}, >( options: { context?: TNewContext; - cache?: TCacheDefinitely; - env?: InferSchemaInputSafe; - } = {}, + cache?: CacheAdapter; + env?: ResolveCallableEnv; + } & TOptions & + Record< + Exclude, + never + > = {} as { + context?: TNewContext; + cache?: CacheAdapter; + env?: ResolveCallableEnv; + } & TOptions & + Record, never>, ) { + type TOptionCache = TOptions[keyof TOptions & "cache"]; + type TProvidedCache = Extract; + type TEffectiveCacheAdapter = "cache" extends keyof TOptions + ? undefined extends TOptionCache + ? TCacheAdapter | TProvidedCache + : TProvidedCache + : TCacheAdapter; + let za = this; if (options.cache) { - za = this.cache(options.cache) as any; + za = this.cache(options.cache) as any; } return za._createProcedure< - TNewCacheAdapter, + TEffectiveCacheAdapter, TIncomingEnv, TNewContext, TKindNames diff --git a/src/is-promise.ts b/src/is-promise.ts index d147941..2555931 100644 --- a/src/is-promise.ts +++ b/src/is-promise.ts @@ -9,7 +9,7 @@ export type IsAny = 0 extends 1 & T ? true : false; /** - * Returns `true` if the supplied value type `V` is a concrete promise. + * Reports whether the supplied value type `V` is definitely, possibly, or never promise-like. * * ## Behavior: * - `string | number | { … }` → `false` @@ -24,25 +24,23 @@ export type IsAny = 0 extends 1 & T ? true : false; * ## Special Notes * - The literal value `any` is explicitly treated as "not a promise" * - However, `Promise` IS detected as a promise (since we know it's wrapped) - * - Uses array wrapper `[T]` to prevent distributive conditional types + * - Mixed promise/non-promise unions produce `boolean` to preserve uncertainty * * @template V - The value type you want to test */ // TEST: with expect-type export type IsPromise = IsAny extends true - ? false // Bare `any` → treat as non-promise - : [V] extends [Promise] - ? true // Explicitly Promise → is a promise + ? false + : [V] extends [never] + ? false : [V] extends [PromiseLike] - ? true // PromiseLike → is a promise - : [Awaited] extends [V] - ? false // Awaiting V gives us V → not a promise - : IsAny> extends true - ? false // If Awaited is any, we can't tell → treat as non-promise - : true; // Awaiting V gives us something different → is a promise + ? true + : [Extract>] extends [never] + ? false + : boolean; /** - * Conditionally wraps a result type in a Promise based on whether the input type is a Promise. + * Preserves sync, async, and possibly-async return shapes from the input type. * * ## Use Case * Perfect for functions that should return `Promise` for async handlers @@ -51,6 +49,7 @@ export type IsPromise = IsAny extends true * ## Behavior: * - `ConditionalAsync, Result>` → `Promise` * - `ConditionalAsync` → `Result` + * - `ConditionalAsync, Result>` → `Result | Promise` * - `ConditionalAsync` → `Result` (bare `any` is treated as sync) * - `ConditionalAsync, Result>` → `Promise` (Promise is treated as async) * @@ -68,6 +67,8 @@ export type IsPromise = IsAny extends true * @template Result - The result type to wrap conditionally */ // TEST: with expect-type -export type ConditionalAsync = IsPromise extends true - ? Promise // Is a promise → wrap in Promise - : Result; // Not a promise (including bare `any`) → return as-is +type ResolvePromise = TAsync extends true + ? Promise + : Result; + +export type ConditionalAsync = ResolvePromise, Result>; diff --git a/src/types.ts b/src/types.ts index 1d2ce33..3e6ceca 100644 --- a/src/types.ts +++ b/src/types.ts @@ -5,6 +5,7 @@ import type { InternalError, ValidationError, } from "./errors"; +import type { IsPromise } from "./is-promise"; export * from "./is-promise"; @@ -12,6 +13,55 @@ export type Schema = StandardSchemaV1; export type AnySchema = Schema; +// TEST: with expect-type +export type IsAsyncSchema = [T] extends [never] + ? false + : T extends unknown + ? "async" extends keyof T + ? [T["async" & keyof T]] extends [true] + ? true + : true extends T["async" & keyof T] + ? boolean + : false + : false + : never; + +type SchemaMapAsyncState = T extends Record + ? true extends { + [K in keyof T]: [IsAsyncSchema] extends [true] ? true : false; + }[keyof T] + ? true + : true extends { + [K in keyof T]: true extends IsAsyncSchema ? true : false; + }[keyof T] + ? boolean + : false + : false; + +type IsDefinitelyAsync = [T] extends [true] ? true : false; +type IsPossiblyAsync = true extends T ? true : false; + +// TEST: with expect-type +export type HasAsyncSchema = + true extends + | IsDefinitelyAsync> + | IsDefinitelyAsync> + | IsDefinitelyAsync> + ? true + : true extends + | IsPossiblyAsync> + | IsPossiblyAsync> + | IsPossiblyAsync> + ? boolean + : false; + +// TEST: with expect-type +export type ConditionalSchemaAsync< + TAsync extends boolean, + TSync, + TAsyncResult, +> = TAsync extends true ? TAsyncResult : TSync; + export type SchemaIssue = StandardSchemaV1.Issue; export type InferSchemaOutput = T extends StandardSchemaV1< @@ -63,53 +113,73 @@ export type IsOptional = undefined extends T ? true : false; export type ObjectToUnion = T[keyof T]; -export type CacheAdapter = - | { - has(key: string): boolean; - get(key: string): unknown; - set(key: string, value: unknown): any; - } - | { - has(key: string): Promise; - get(key: string): Promise; - // NOTE: if we gotta be strict, it should be Promise or Promise - // but it's fine, cuz we don't really care and we never await it anyway - // NOTE: Making it the same as the "sync version" above - // allows end users to provide CacheAdapters with mixed sync & async methods, - // without reporting them an error, because we allow and handle - // ALL the cases at runtime anyway - set(key: string, value: unknown): any; - }; +export type CacheAdapter = { + has(key: string): boolean | Promise; + get(key: string): unknown; + set(key: string, value: unknown): any; +}; + +// TEST: with expect-type +export type HasAsyncCache = TCache extends { + has(key: string): infer THas; + get(key: string): infer TGet; + set(key: string, value: unknown): infer TSet; +} + ? true extends + | IsDefinitelyAsync> + | IsDefinitelyAsync> + | IsDefinitelyAsync> + ? true + : true extends + | IsPossiblyAsync> + | IsPossiblyAsync> + | IsPossiblyAsync> + ? boolean + : false + : false; + +// Cache methods run only on the paths that need them, so even a definitely +// async method makes the procedure possibly async rather than always async. +export type ConditionalCacheAsync = [ + HasAsyncCache, +] extends [false] + ? TResult + : TResult | Promise>; // TEST: with expect-type export type ZagoraResult< TOutput, TErrorsMap extends Record | any, TResolvedResult, - IsTypedError = TErrorsMap extends Record ? true : false, + IsTypedError = TErrorsMap extends Record ? boolean : false, > = TResolvedResult extends { readonly ok: true } ? { readonly ok: true; data: TOutput; readonly error: undefined; } - : TErrorsMap extends Record - ? { - readonly ok: false; - readonly isTypedError: IsTypedError; - readonly error: - | Prettify< - Readonly< - Prettify>> - > + : IsTypedError extends true + ? TErrorsMap extends Record + ? { + readonly ok: false; + readonly isTypedError: true; + readonly error: Prettify< + Readonly< + Prettify>> > - | ValidationError - | InternalError; - } + >; + } + : never : { readonly ok: false; - readonly isTypedError: IsTypedError; - readonly error: InternalError | ValidationError; + readonly isTypedError: false; + readonly error: + | InternalError + | ValidationError< + TErrorsMap extends Record + ? keyof TErrorsMap + : never + >; }; export interface ZagoraDef< diff --git a/src/utils.ts b/src/utils.ts index 2be114c..b9d4fab 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -6,24 +6,39 @@ export function getCacheHash(data: string) { return nodeCrypto.createHash("sha256").update(data).digest("hex"); } +function createUnexpectedValidationError( + mode: "input" | "output" | "error data" | "env", + cause: unknown, +) { + return createResult( + null, + createInternalError(`Unexpected failure during ${mode} validation`, cause), + false, + ); +} + // TEST: with expect-type export function validateInputOutputOrEnv( mode: "input" | "output" | "env", schema: any, data: any, ) { - const result = schema["~standard"].validate(data); - if (result instanceof Promise) { - return result.then((or) => - or.issues - ? createResult(null, createValidationError(mode, or.issues), false) - : createResult(or.value, null, false), - ); - } + const processResult = (result: any) => + result.issues + ? createResult(null, createValidationError(mode, result.issues), false) + : createResult(result.value, null, false); - return result.issues - ? createResult(null, createValidationError(mode, result.issues), false) - : createResult(result.value, null, false); + try { + const result = schema["~standard"].validate(data); + if (result instanceof Promise) { + return result + .then(processResult) + .catch((error) => createUnexpectedValidationError(mode, error)); + } + return processResult(result); + } catch (error) { + return createUnexpectedValidationError(mode, error); + } } // TEST: with expect-type @@ -44,11 +59,21 @@ export function validateError( } const kind = error?.kind; - if (kind != null && Object.hasOwn(errorsMap, kind)) { + if (kind == null) { + return createResult( + null, + createInternalError( + `${isAsync ? "Async" : "Sync"} handler threw unknown error`, + error, + ), + false, + ); + } + + if (Object.hasOwn(errorsMap, kind)) { const kindName = kind as TKindNames; const schema = errorsMap[kindName as any] as any; const { kind: _, ...cleanedError } = error; - const result = schema["~standard"].validate(cleanedError); const processError = (res: any) => res.issues ? createResult( @@ -60,17 +85,29 @@ export function validateError( ), false, ) - : createResult(null, { kind, ...res.value } as const, true); + : createResult(null, { ...res.value, kind } as const, true); - if (result instanceof Promise) { - return result.then(processError); + try { + const result = schema["~standard"].validate(cleanedError); + if (result instanceof Promise) { + return result + .then(processError) + .catch((error) => + createUnexpectedValidationError("error data", error), + ); + } + return processError(result); + } catch (error) { + return createUnexpectedValidationError("error data", error); } - return processError(result); } return createResult( null, - createInternalError(`Typed Error ${kind} is not defined in errors map`), + createInternalError( + `Typed Error ${kind} is not defined in errors map`, + error, + ), false, ); } @@ -188,8 +225,13 @@ export function tryCatch(fn: any, isHandler: boolean, method: string = "") { .then((data) => createResult(data, null, false)) .catch((error) => { if (isHandler) { - const res = createResult(null, error, false); - return { ...res, handlerFailed: true, isAsync: true }; + return { + ok: false as const, + isTypedError: false as const, + error, + handlerFailed: true, + isAsync: true, + }; } return createResult( null, @@ -204,8 +246,13 @@ export function tryCatch(fn: any, isHandler: boolean, method: string = "") { return createResult(res, null, false); } catch (error: unknown) { if (isHandler) { - const res = createResult(null, error, false); - return { ...res, handlerFailed: true, isAsync: false }; + return { + ok: false as const, + isTypedError: false as const, + error, + handlerFailed: true, + isAsync: false, + }; } return createResult( @@ -222,7 +269,7 @@ export function createResult(data: any, error: any, isTypedError: boolean) { return { ok: false, isTypedError, error: Object.freeze(error) } as const; } - return { ok: true, data } as const; + return { ok: true, data, error: undefined } as const; } // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: it's fine @@ -268,29 +315,29 @@ export function handleTupleDefaults( return rawArgs; } -function isPlainObject(obj: any) { - return obj && typeof obj === "object"; +function isPlainObject(value: unknown): value is Record { + if (value === null || typeof value !== "object") { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; } -export function deepMerge(aaa: any, bbb: any) { - if (!isPlainObject(aaa)) { - throw new Error("Expects an object args"); +export function deepMerge( + base: Record, + override: Record, +) { + if (!isPlainObject(base) || !isPlainObject(override)) { + throw new Error("Expects plain object args"); } - const result = { ...aaa }; + const result: Record = { ...base }; - if (!isPlainObject(bbb)) { - return result; - } - - for (const key in bbb) { - if (Object.hasOwn(bbb, key)) { - if (isPlainObject(result[key]) && isPlainObject(bbb[key])) { - result[key] = deepMerge(result[key], bbb[key]); - } else { - result[key] = bbb[key]; - } - } + for (const key of Object.keys(override)) { + result[key] = + isPlainObject(result[key]) && isPlainObject(override[key]) + ? deepMerge(result[key], override[key]) + : override[key]; } return result; diff --git a/test/contracts.test.ts b/test/contracts.test.ts new file mode 100644 index 0000000..d4c95ec --- /dev/null +++ b/test/contracts.test.ts @@ -0,0 +1,351 @@ +// SPDX-License-Identifier: Apache-2.0 + +import type { StandardSchemaV1 } from "@standard-schema/spec"; +import * as v from "valibot"; +import { expect, test } from "vitest"; +import z from "zod"; +import { createErrorHelpers } from "../src/errors"; +import { zagora } from "../src/index"; +import { createResult } from "../src/utils"; + +type Schema = StandardSchemaV1; + +function schema( + validate: StandardSchemaV1.Props["validate"], +): Schema { + return { + "~standard": { + version: 1, + vendor: "test", + validate, + }, + }; +} + +function asyncSchema( + validate: StandardSchemaV1.Props["validate"], +): Schema & { readonly async: true } { + return { ...schema(validate), async: true }; +} + +function expectInternalError(result: any, cause: unknown) { + expect(result).toMatchObject({ + ok: false, + isTypedError: false, + error: { + kind: "UNKNOWN_ERROR", + cause, + }, + }); +} + +test("schema implementation failures become internal results", async () => { + const inputCause = new Error("input exploded"); + let handlerCalls = 0; + const inputProcedure = zagora() + .input( + schema(() => { + throw inputCause; + }), + ) + .handler((_, input) => { + handlerCalls += 1; + return input; + }) + .callable(); + + const inputResult = inputProcedure("input"); + expectInternalError(inputResult, inputCause); + expect(handlerCalls).toBe(0); + + const outputCause = new Error("output exploded"); + const outputProcedure = zagora() + .input(z.string()) + .output(asyncSchema(() => Promise.reject(outputCause))) + .handler((_, input) => input) + .callable(); + + expectInternalError(await outputProcedure("output"), outputCause); + + const envCause = new Error("env exploded"); + const envProcedure = zagora() + .env( + schema, Record>(() => { + throw envCause; + }), + {}, + ) + .handler(({ env }) => env) + .callable(); + + expectInternalError(envProcedure(), envCause); + + const syncErrorCause = new Error("error schema exploded"); + const syncErrorProcedure = zagora() + .errors({ + FAILURE: schema<{ message: string }, { message: string }>(() => { + throw syncErrorCause; + }), + }) + .handler(({ errors }) => { + throw errors.FAILURE({ message: "failure" }); + }) + .callable(); + + expectInternalError(syncErrorProcedure(), syncErrorCause); + + const asyncErrorCause = new Error("async error schema exploded"); + const asyncErrorProcedure = zagora() + .errors({ + FAILURE: asyncSchema<{ message: string }, { message: string }>(() => + Promise.reject(asyncErrorCause), + ), + }) + .handler(({ errors }) => { + throw errors.FAILURE({ message: "failure" }); + }) + .callable(); + + expectInternalError(await asyncErrorProcedure(), asyncErrorCause); +}); + +test.each([ + undefined, + null, + false, + 0, + "", +])("a handler throwing %j still returns a failure", (thrown) => { + const procedure = zagora() + .input(z.boolean()) + .handler((_, shouldThrow) => { + if (shouldThrow) { + throw thrown; + } + return "ok"; + }) + .callable(); + + const result = procedure(true); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.isTypedError).toBe(false); + expect(result.error.kind).toBe("UNKNOWN_ERROR"); + if (result.error.kind === "UNKNOWN_ERROR") { + expect(result.error.cause).toBe(thrown); + } + } +}); + +test("context merges plain containers and preserves dependencies", () => { + class Database { + constructor(readonly name: string) {} + + query() { + return this.name; + } + } + + type Context = { + db: Database; + config: { timeout?: number; retries?: number }; + }; + + const production = new Database("production"); + const testDatabase = new Database("test"); + const initialContext: Context = { + db: production, + config: { timeout: 5, retries: 1 }, + }; + const procedure = zagora() + .context(initialContext) + .handler(({ context }) => ({ + db: context.db, + name: context.db.query(), + config: context.config, + })) + .callable({ + context: { + db: testDatabase, + config: { retries: 2 }, + }, + }); + + const result = procedure(); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.data.db).toBe(testDatabase); + expect(result.data.db).toBeInstanceOf(Database); + expect(result.data.name).toBe("test"); + expect(result.data.config).toEqual({ timeout: 5, retries: 2 }); + } +}); + +test("callable context works without an initial context value", () => { + class Database { + query() { + return "ok"; + } + } + + const db = new Database(); + const procedure = zagora() + .context<{ db: Database }>() + .handler(({ context }) => context.db.query()) + .callable({ context: { db } }); + + const result = procedure(); + expect(result).toMatchObject({ ok: true, data: "ok" }); +}); + +test("error helpers only use own keys and preserve the declared kind", () => { + const errorSchema = z.object({ message: z.string() }); + const errorMap = Object.assign(Object.create({ INHERITED: errorSchema }), { + DECLARED: errorSchema, + }); + const helpers = createErrorHelpers(errorMap); + + expect(Object.keys(helpers)).toEqual(["DECLARED"]); + expect(helpers.DECLARED?.({ kind: "OTHER", message: "failure" })).toEqual({ + kind: "DECLARED", + message: "failure", + }); +}); + +test("error validation cannot replace the declared kind", () => { + const procedure = zagora() + .errors({ + DECLARED: schema<{ message: string }, { message: string; kind: string }>( + (value) => ({ + value: { ...(value as { message: string }), kind: "OTHER" }, + }), + ), + }) + .handler(({ errors }) => { + throw errors.DECLARED({ message: "failure" }); + }) + .callable(); + + expect(procedure()).toMatchObject({ + ok: false, + isTypedError: true, + error: { kind: "DECLARED", message: "failure" }, + }); +}); + +test.each([ + new Error("failure"), + undefined, +])("untyped handler throws remain unknown errors when an error map exists", (thrown) => { + const procedure = zagora() + .errors({ DECLARED: z.object({ message: z.string() }) }) + .handler(() => { + throw thrown; + }) + .callable(); + + const result = procedure(); + expectInternalError(result, thrown); +}); + +test("success results expose the shape promised by their type", () => { + const result = createResult("ok", null, false); + expect(result).toEqual({ ok: true, data: "ok", error: undefined }); + expect(Object.hasOwn(result, "error")).toBe(true); +}); + +test("maybe-Promise handlers preserve their runtime branch", async () => { + const procedure = zagora() + .input(z.enum(["sync", "async"])) + .handler((_, mode) => (mode === "async" ? Promise.resolve(mode) : mode)) + .callable(); + + const syncResult = procedure("sync"); + expect(syncResult).not.toBeInstanceOf(Promise); + expect(syncResult).toMatchObject({ ok: true, data: "sync" }); + + const asyncResult = procedure("async"); + expect(asyncResult).toBeInstanceOf(Promise); + expect(await asyncResult).toMatchObject({ ok: true, data: "async" }); +}); + +test("async cache methods only make paths that invoke them async", async () => { + const cache = { + has() { + return false; + }, + get() { + return undefined; + }, + async set() {}, + }; + const procedure = zagora() + .cache(cache) + .input(z.string()) + .handler((_, input) => input) + .callable(); + + const invalidResult = procedure(123 as any); + expect(invalidResult).not.toBeInstanceOf(Promise); + if (invalidResult instanceof Promise) { + throw new Error("Invalid input should fail before the cache is invoked"); + } + expect(invalidResult.ok).toBe(false); + + const validResult = procedure("valid"); + expect(validResult).toBeInstanceOf(Promise); + expect((await validResult).ok).toBe(true); +}); + +test("an async error-map entry makes every runtime path async", async () => { + const procedure = zagora() + .input(v.string()) + .errors({ + SYNC_ERROR: v.object({ message: v.string() }), + ASYNC_ERROR: v.pipeAsync( + v.object({ message: v.string() }), + v.checkAsync(async () => true), + ), + }) + .handler(({ errors }, input) => { + if (input === "sync-error") { + throw errors.SYNC_ERROR({ message: input }); + } + if (input === "async-error") { + throw errors.ASYNC_ERROR({ message: input }); + } + return input; + }) + .callable(); + + const invalidResult = procedure(123 as any); + const successResult = procedure("success"); + const syncErrorResult = procedure("sync-error"); + const asyncErrorResult = procedure("async-error"); + + for (const result of [ + invalidResult, + successResult, + syncErrorResult, + asyncErrorResult, + ]) { + expect(result).toBeInstanceOf(Promise); + } + + expect(await invalidResult).toMatchObject({ + ok: false, + isTypedError: false, + error: { kind: "VALIDATION_ERROR" }, + }); + expect(await successResult).toMatchObject({ ok: true, data: "success" }); + expect(await syncErrorResult).toMatchObject({ + ok: false, + isTypedError: true, + error: { kind: "SYNC_ERROR", message: "sync-error" }, + }); + expect(await asyncErrorResult).toMatchObject({ + ok: false, + isTypedError: true, + error: { kind: "ASYNC_ERROR", message: "async-error" }, + }); +}); diff --git a/test/main.test.ts b/test/main.test.ts index 5bad848..8cda383 100644 --- a/test/main.test.ts +++ b/test/main.test.ts @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +import * as v from "valibot"; import { expect, expectTypeOf, test } from "vitest"; import z from "zod"; import { @@ -186,6 +187,70 @@ test("async output schema", async () => { } }); +test("Valibot async schemas always return promises", async () => { + const asyncOutput = v.pipeAsync( + v.string(), + v.checkAsync(async (value) => value !== "bad"), + ); + const outputProcedure = zagora() + .input(v.string()) + .output(asyncOutput) + .handler((_, input) => input) + .callable(); + + const invalidInputResult = outputProcedure(123 as any); + expect(invalidInputResult).toBeInstanceOf(Promise); + expect((await invalidInputResult).ok).toBe(false); + + const invalidOutputResult = outputProcedure("bad"); + expect(invalidOutputResult).toBeInstanceOf(Promise); + expect((await invalidOutputResult).ok).toBe(false); + + const asyncError = v.pipeAsync( + v.object({ message: v.string() }), + v.checkAsync(async () => true), + ); + const errorProcedure = zagora() + .input(v.string()) + .errors({ ASYNC_ERROR: asyncError }) + .handler(({ errors }, input) => { + if (input === "fail") { + throw errors.ASYNC_ERROR({ message: "failed" }); + } + return input; + }) + .callable(); + + const successResult = errorProcedure("success"); + expect(successResult).toBeInstanceOf(Promise); + expect((await successResult).ok).toBe(true); + + const failedErrorResult = errorProcedure("fail"); + expect(failedErrorResult).toBeInstanceOf(Promise); + expect((await failedErrorResult).ok).toBe(false); +}); + +test("union-typed Valibot schemas preserve runtime return shape", async () => { + const syncSchema = v.string(); + const asyncSchema = v.pipeAsync( + v.string(), + v.checkAsync(async () => true), + ); + const createProcedure = (schema: typeof syncSchema | typeof asyncSchema) => + zagora() + .input(schema) + .handler((_, input) => input) + .callable(); + + const syncResult = createProcedure(syncSchema)("sync"); + expect(syncResult).not.toBeInstanceOf(Promise); + expect((await syncResult).ok).toBe(true); + + const asyncResult = createProcedure(asyncSchema)("async"); + expect(asyncResult).toBeInstanceOf(Promise); + expect((await asyncResult).ok).toBe(true); +}); + test("handleError with async schema validation", async () => { const asyncErrorSchema = z.object({ message: z diff --git a/test/types-testing.test.ts b/test/types-testing.test.ts index 2391226..ea3bb0c 100644 --- a/test/types-testing.test.ts +++ b/test/types-testing.test.ts @@ -19,15 +19,16 @@ * * ## Edge cases covered: * - * - `never` type extends everything (including Promise), so IsPromise = true - * - Union types with Promise (e.g., `string | Promise`) are treated as promise-like + * - `never` represents no runtime value, so IsPromise = false + * - Union types with Promise preserve uncertainty instead of collapsing to true or false * - Bare `any` is explicitly treated as non-promise, but `Promise` is a promise * - Optional tuple parameters and their overload signatures * - * Run with: `bun run typecheck` + * Run with: `bun run check:types` */ import type { StandardSchemaV1 } from "@standard-schema/spec"; +import * as v from "valibot"; import { expect, expectTypeOf, test } from "vitest"; import { z } from "zod"; import type { @@ -40,9 +41,14 @@ import type { import { Zagora, zagora } from "../src/index"; import type { AnySchema, + CacheAdapter, ConditionalAsync, + ConditionalSchemaAsync, + HasAsyncCache, + HasAsyncSchema, InferSchemaOutputSafe, IsAny, + IsAsyncSchema, IsOptional, IsPromise, ResolvedProcedure, @@ -54,6 +60,7 @@ import type { } from "../src/types"; import { createResult, + deepMerge, validateError, type validateInputOutputOrEnv, } from "../src/utils"; @@ -111,16 +118,16 @@ test("IsPromise - detects Promise and PromiseLike types", () => { expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); - // `never` extends everything including Promise, so it's detected as a promise - expectTypeOf>().toEqualTypeOf(); + // A function that never returns is not asynchronous by itself. + expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); - // Should handle union types - unions with Promise are detected as promise-like - // because Awaited> = string | number, which differs from the input - expectTypeOf>>().toEqualTypeOf(); + // A union with a Promise is possibly async, regardless of its resolved value. + expectTypeOf>>().toEqualTypeOf(); + expectTypeOf>>().toEqualTypeOf(); }); // ============================================================================= @@ -156,6 +163,296 @@ test("ConditionalAsync - conditionally wraps result in Promise", () = expectTypeOf, string>>().toEqualTypeOf< Promise >(); + + // Should preserve uncertainty when only some branches return a Promise. + expectTypeOf< + ConditionalAsync, { data: string }> + >().toEqualTypeOf<{ data: string } | Promise<{ data: string }>>(); +}); + +test("Valibot async schemas produce async procedure types", () => { + const syncSchema = v.string(); + const asyncSchema = v.pipeAsync( + v.string(), + v.checkAsync(async (value) => value.length > 0), + ); + + type MixedSchema = typeof syncSchema | typeof asyncSchema; + type OptionalAsyncSchema = StandardSchemaV1 & { + readonly async?: true; + }; + + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema< + undefined, + undefined, + { SYNC: typeof syncSchema; ASYNC: typeof asyncSchema } + > + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema< + undefined, + undefined, + { VALUE: typeof syncSchema } | { VALUE: typeof asyncSchema } + > + >().toEqualTypeOf(); + expectTypeOf< + ConditionalSchemaAsync + >().toEqualTypeOf<"sync" | "async">(); + + const syncProcedure = zagora() + .input(syncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncInputProcedure = zagora() + .input(asyncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const createMixedProcedure = (schema: MixedSchema) => + zagora() + .input(schema) + .handler((_, input) => input) + .callable(); + const mixedProcedure = createMixedProcedure(syncSchema); + expectTypeOf>().toEqualTypeOf< + ReturnType | ReturnType + >(); + + const asyncOutputProcedure = zagora() + .input(syncSchema) + .output(asyncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncErrorProcedure = zagora() + .input(syncSchema) + .errors({ SYNC_ERROR: syncSchema, ASYNC_ERROR: asyncSchema }) + .handler(({ errors }, input) => { + if (input === "sync") { + throw errors.SYNC_ERROR(input); + } + if (!input) { + throw errors.ASYNC_ERROR(input); + } + return input; + }) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + type MixedErrorsMap = + | { SYNC_ERROR: typeof syncSchema } + | { ASYNC_ERROR: typeof asyncSchema }; + const createMixedErrorsMapProcedure = (errorsMap: MixedErrorsMap) => + zagora() + .input(syncSchema) + .errors(errorsMap) + .handler((_, input) => input) + .callable(); + const mixedErrorsMapProcedure = createMixedErrorsMapProcedure({ + SYNC_ERROR: syncSchema, + }); + type MixedErrorsMapResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + const autoCallableProcedure = zagora({ + autoCallable: true, + disableOptions: true, + }) + .input(asyncSchema) + .handler((input) => input); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const createMixedAutoCallable = (schema: MixedSchema) => + zagora({ autoCallable: true, disableOptions: true }) + .input(schema) + .handler((input) => input); + const mixedAutoCallableProcedure = createMixedAutoCallable(syncSchema); + expectTypeOf>().toEqualTypeOf< + ReturnType + >(); +}); + +test("handler and cache Promise branches stay visible in procedure types", () => { + const syncCache = { + has() { + return false; + }, + get() { + return undefined; + }, + set() {}, + }; + const asyncHasCache = { + async has() { + return false; + }, + get() { + return undefined; + }, + set() {}, + }; + const asyncGetCache = { + has() { + return true; + }, + async get() { + return "cached"; + }, + set() {}, + }; + const asyncSetCache = { + has() { + return false; + }, + get() { + return undefined; + }, + async set() {}, + }; + + const mixedAdapter: CacheAdapter = asyncHasCache; + expectTypeOf(mixedAdapter).toExtend(); + + type MaybeAsyncHasCache = { + has(key: string): boolean | Promise; + get(key: string): undefined; + set(key: string, value: unknown): void; + }; + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + HasAsyncCache + >().toEqualTypeOf(); + + const syncCachedProcedure = zagora() + .cache(syncCache) + .input(v.string()) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const builderCachedProcedure = zagora() + .cache(asyncSetCache) + .input(v.string()) + .handler((_, input) => input) + .callable(); + type BuilderCachedResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + const callableCachedProcedure = zagora() + .input(v.string()) + .handler((_, input) => input) + .callable({ cache: asyncHasCache }); + type CallableCachedResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + const autoCachedProcedure = zagora({ + autoCallable: true, + disableOptions: true, + }) + .cache(asyncGetCache) + .input(v.string()) + .handler((input) => input); + type AutoCachedResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + const cacheConfigurableProcedure = zagora() + .cache(asyncSetCache) + .input(v.string()) + .handler((_, input) => input); + + const syncOverrideProcedure = cacheConfigurableProcedure.callable({ + cache: syncCache, + }); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const optionalSyncOverride: { cache?: typeof syncCache } = {}; + const optionallyOverriddenProcedure = + cacheConfigurableProcedure.callable(optionalSyncOverride); + type OptionallyOverriddenResult = ReturnType< + typeof optionallyOverriddenProcedure + >; + expectTypeOf().toEqualTypeOf< + | Awaited + | Promise> + >(); + + const undefinedOverrideProcedure = cacheConfigurableProcedure.callable({ + cache: undefined, + }); + type UndefinedOverrideResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + // @ts-expect-error callable options reject unknown properties + cacheConfigurableProcedure.callable({ cache: syncCache, typo: true }); + + const maybeHandlerProcedure = zagora() + .input(v.string()) + .handler((_, input) => (input.length > 0 ? input : Promise.resolve(input))) + .callable(); + type MaybeHandlerResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + + const asyncSchemaAndCacheProcedure = zagora() + .cache(asyncSetCache) + .input( + v.pipeAsync( + v.string(), + v.checkAsync(async () => true), + ), + ) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); }); // ============================================================================= @@ -254,10 +551,36 @@ test("ZagoraResult<...> - result type structure for success/error cases", () => TestErrorsMap, { readonly ok: false } >; - expectTypeOf().toMatchObjectType<{ - readonly ok: false; - readonly isTypedError: true; - }>(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf< + Extract["isTypedError"] + >().toEqualTypeOf(); + expectTypeOf< + Extract["isTypedError"] + >().toEqualTypeOf(); + + const invalidSchema = z.object({ message: z.string() }); + const missingSchema = z.object({ id: z.number() }); + type ConcreteErrorsMap = { + NOT_VALID: typeof invalidSchema; + NOT_FOUND: typeof missingSchema; + }; + type ConcreteError = ZagoraResult< + string, + ConcreteErrorsMap, + { readonly ok: false } + >; + expectTypeOf< + Extract["error"] + >().toEqualTypeOf< + | { readonly kind: "NOT_VALID"; readonly message: string } + | { readonly kind: "NOT_FOUND"; readonly id: number } + >(); + expectTypeOf< + Extract["error"] + >().toEqualTypeOf< + InternalError | ValidationError<"NOT_VALID" | "NOT_FOUND"> + >(); }); // ============================================================================= @@ -600,6 +923,22 @@ test("Zagora procedures - sync handler return types", () => { } }); +test("declared error kinds override transformed schema output kinds", () => { + const transformedError = z + .object({ message: z.string() }) + .transform(({ message }) => ({ kind: "OTHER" as const, message })); + + type ResolvedError = InferSchemaMapPlain< + { DECLARED: typeof transformedError }, + true + >["DECLARED"]; + + expectTypeOf().toEqualTypeOf<{ + kind: "DECLARED"; + message: string; + }>(); +}); + test("Zagora procedures - async handler return types", async () => { const someJson = `{"name": "zagora"}`; const safeAsyncParse = zagora() @@ -690,6 +1029,56 @@ test("type test zagora options", () => { }); }); +test("context and deepMerge only accept record-shaped roots", () => { + interface InterfaceContext { + value: string; + } + + const interfaceContext = { value: "interface" } as InterfaceContext; + + const assertInvalidRoots = () => { + // @ts-expect-error interface-shaped roots are intentionally unsupported + zagora().context(interfaceContext); + // @ts-expect-error context roots must be records + zagora().context(new Date()); + // @ts-expect-error context roots must be records + zagora().context("invalid"); + // @ts-expect-error deepMerge roots must be records + deepMerge(new Date(), {}); + // @ts-expect-error deepMerge roots must be records + deepMerge("invalid", {}); + }; + + expectTypeOf(assertInvalidRoots).toBeFunction(); +}); + +test("callable env accepts indexed sources only after declaring a schema", () => { + const indexedEnv: Record = { + PORT: "3000", + }; + + zagora() + .env(z.object({ PORT: z.string().optional() })) + .handler(({ env }) => env.PORT) + .callable({ env: indexedEnv }); + + const exactEnvProcedure = zagora() + .env(z.object({ PORT: z.string() })) + .handler(({ env }) => env.PORT); + + exactEnvProcedure.callable({ + // @ts-expect-error finite env objects reject keys absent from the schema + env: { PORT: "3000", TYPO: "unexpected" }, + }); + + zagora() + .handler(() => undefined) + // @ts-expect-error runtime env requires a declared env schema + .callable({ + env: { PORT: "3000" }, + }); +}); + test("should have ~zagora property typed correctly on buiulder and on callable", () => { const procedure = zagora() .input(z.string()) diff --git a/test/utils.test.ts b/test/utils.test.ts index bea8399..1ced22b 100644 --- a/test/utils.test.ts +++ b/test/utils.test.ts @@ -131,3 +131,31 @@ test("deepMerge - merge nested objects", () => { expect(result.b.e).toBe(5); expect(result.f).toBe(6); }); + +test("deepMerge - replace complex values from the source", () => { + class Database { + constructor(readonly name: string) {} + } + + const originalDate = new Date("2025-01-01"); + const replacementDate = new Date("2026-01-01"); + const originalDatabase = new Database("production"); + const replacementDatabase = new Database("test"); + + const result = deepMerge( + { + createdAt: originalDate, + db: originalDatabase, + nested: { keep: true, db: originalDatabase }, + }, + { + createdAt: replacementDate, + db: replacementDatabase, + nested: { db: "mock" }, + }, + ); + + expect(result.createdAt).toBe(replacementDate); + expect(result.db).toBe(replacementDatabase); + expect(result.nested).toEqual({ keep: true, db: "mock" }); +});