convex 1.42.2 → 1.43.0-alpha.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 +8 -1
- package/bin/main-dev +6 -1
- package/dist/browser.bundle.js +49 -10
- package/dist/browser.bundle.js.map +2 -2
- package/dist/cjs/browser/index.js.map +2 -2
- package/dist/cjs/browser/simple_client-node.js +35 -35
- package/dist/cjs/browser/simple_client-node.js.map +2 -2
- package/dist/cjs/browser/sync/client.js.map +1 -1
- package/dist/cjs/browser/sync/paginated_query_client.js +20 -9
- package/dist/cjs/browser/sync/paginated_query_client.js.map +2 -2
- package/dist/cjs/cli/codegen_templates/component_api.js +2 -2
- package/dist/cjs/cli/codegen_templates/component_api.js.map +2 -2
- package/dist/cjs/cli/codegen_templates/validator_helpers.js +2 -0
- package/dist/cjs/cli/codegen_templates/validator_helpers.js.map +2 -2
- package/dist/cjs/cli/deployment.js +2 -1
- package/dist/cjs/cli/deployment.js.map +2 -2
- package/dist/cjs/cli/deploymentCreate.js.map +2 -2
- package/dist/cjs/cli/generatedApi.js.map +1 -1
- package/dist/cjs/cli/lib/deployApi/validator.js +1 -0
- package/dist/cjs/cli/lib/deployApi/validator.js.map +2 -2
- package/dist/cjs/cli/lib/deploymentSelection.js.map +2 -2
- package/dist/cjs/cli/lib/generateDocs.js +1 -1
- package/dist/cjs/cli/lib/generateDocs.js.map +2 -2
- package/dist/cjs/cli/lib/generatedFunctionLogsApi.js.map +1 -1
- package/dist/cjs/cli/lib/localDeployment/projectMismatch.js.map +2 -2
- package/dist/cjs/cli/lib/login.js +23 -23
- package/dist/cjs/cli/lib/login.js.map +2 -2
- package/dist/cjs/cli/lib/typecheck.js +28 -25
- package/dist/cjs/cli/lib/typecheck.js.map +2 -2
- package/dist/cjs/cli/lib/usageLimits.js +164 -0
- package/dist/cjs/cli/lib/usageLimits.js.map +7 -0
- package/dist/cjs/cli/usageLimits.js +326 -0
- package/dist/cjs/cli/usageLimits.js.map +7 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react/client.js.map +2 -2
- package/dist/cjs/server/components/index.js.map +2 -2
- package/dist/cjs/server/cron.js +33 -29
- package/dist/cjs/server/cron.js.map +2 -2
- package/dist/cjs/server/database.js.map +1 -1
- package/dist/cjs/server/impl/database_impl.js +3 -0
- package/dist/cjs/server/impl/database_impl.js.map +2 -2
- package/dist/cjs/server/log.js +2 -1
- package/dist/cjs/server/log.js.map +2 -2
- package/dist/cjs/server/logVars.js +12 -1
- package/dist/cjs/server/logVars.js.map +2 -2
- package/dist/cjs/server/meta.js.map +1 -1
- package/dist/cjs/values/compare.js +5 -1
- package/dist/cjs/values/compare.js.map +2 -2
- package/dist/cjs/values/index.js +1 -0
- package/dist/cjs/values/index.js.map +2 -2
- package/dist/cjs/values/size.js +4 -0
- package/dist/cjs/values/size.js.map +2 -2
- package/dist/cjs/values/validator.js +11 -0
- package/dist/cjs/values/validator.js.map +2 -2
- package/dist/cjs/values/validators.js +20 -0
- package/dist/cjs/values/validators.js.map +2 -2
- package/dist/cjs/values/value.js +31 -0
- package/dist/cjs/values/value.js.map +2 -2
- package/dist/cjs-types/browser/index.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/paginated_query_client.d.ts +1 -38
- package/dist/cjs-types/browser/sync/paginated_query_client.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen_templates/component_api.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen_templates/validator_helpers.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen_templates/validator_helpers.test.d.ts +2 -0
- package/dist/cjs-types/cli/codegen_templates/validator_helpers.test.d.ts.map +1 -0
- package/dist/cjs-types/cli/deployment.d.ts.map +1 -1
- package/dist/cjs-types/cli/deploymentCreate.d.ts +2 -2
- package/dist/cjs-types/cli/generatedApi.d.ts +43 -43
- package/dist/cjs-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deployApi/validator.d.ts +6 -0
- package/dist/cjs-types/cli/lib/deployApi/validator.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deploymentSelection.d.ts +2 -2
- package/dist/cjs-types/cli/lib/deploymentSelection.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts +45 -45
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/projectMismatch.d.ts +2 -2
- package/dist/cjs-types/cli/lib/localDeployment/projectMismatch.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/login.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/mcp/tools/insights.d.ts +24 -24
- package/dist/cjs-types/cli/lib/typecheck.d.ts +2 -0
- package/dist/cjs-types/cli/lib/typecheck.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/typecheck.test.d.ts +2 -0
- package/dist/cjs-types/cli/lib/typecheck.test.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/usageLimits.d.ts +46 -0
- package/dist/cjs-types/cli/lib/usageLimits.d.ts.map +1 -0
- package/dist/cjs-types/cli/usageLimits.d.ts +22 -0
- package/dist/cjs-types/cli/usageLimits.d.ts.map +1 -0
- package/dist/cjs-types/index.d.ts +1 -1
- package/dist/cjs-types/index.d.ts.map +1 -1
- package/dist/cjs-types/react/client.d.ts.map +1 -1
- package/dist/cjs-types/server/components/index.d.ts +26 -8
- package/dist/cjs-types/server/components/index.d.ts.map +1 -1
- package/dist/cjs-types/server/cron.d.ts +20 -11
- package/dist/cjs-types/server/cron.d.ts.map +1 -1
- package/dist/cjs-types/server/cron.test.d.ts +2 -0
- package/dist/cjs-types/server/cron.test.d.ts.map +1 -0
- package/dist/cjs-types/server/database.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/database_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/log.d.ts.map +1 -1
- package/dist/cjs-types/server/logVars.d.ts +14 -1
- package/dist/cjs-types/server/logVars.d.ts.map +1 -1
- package/dist/cjs-types/server/meta.d.ts +2 -2
- package/dist/cjs-types/server/meta.d.ts.map +1 -1
- package/dist/cjs-types/values/compare.d.ts.map +1 -1
- package/dist/cjs-types/values/index.d.ts +2 -2
- package/dist/cjs-types/values/index.d.ts.map +1 -1
- package/dist/cjs-types/values/size.d.ts +1 -1
- package/dist/cjs-types/values/size.d.ts.map +1 -1
- package/dist/cjs-types/values/validator.d.ts +10 -1
- package/dist/cjs-types/values/validator.d.ts.map +1 -1
- package/dist/cjs-types/values/validators.d.ts +14 -3
- package/dist/cjs-types/values/validators.d.ts.map +1 -1
- package/dist/cjs-types/values/value.d.ts +18 -1
- package/dist/cjs-types/values/value.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +2327 -1866
- package/dist/cli.bundle.cjs.map +4 -4
- package/dist/esm/browser/index.js.map +2 -2
- package/dist/esm/browser/simple_client-node.js +35 -35
- package/dist/esm/browser/simple_client-node.js.map +1 -1
- package/dist/esm/browser/sync/client.js.map +1 -1
- package/dist/esm/browser/sync/paginated_query_client.js +20 -9
- package/dist/esm/browser/sync/paginated_query_client.js.map +2 -2
- package/dist/esm/cli/codegen_templates/component_api.js +8 -3
- package/dist/esm/cli/codegen_templates/component_api.js.map +2 -2
- package/dist/esm/cli/codegen_templates/validator_helpers.js +2 -0
- package/dist/esm/cli/codegen_templates/validator_helpers.js.map +2 -2
- package/dist/esm/cli/deployment.js +2 -1
- package/dist/esm/cli/deployment.js.map +2 -2
- package/dist/esm/cli/deploymentCreate.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/validator.js +1 -0
- package/dist/esm/cli/lib/deployApi/validator.js.map +2 -2
- package/dist/esm/cli/lib/deploymentSelection.js.map +2 -2
- package/dist/esm/cli/lib/generateDocs.js +1 -1
- package/dist/esm/cli/lib/generateDocs.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/projectMismatch.js.map +2 -2
- package/dist/esm/cli/lib/login.js +23 -23
- package/dist/esm/cli/lib/login.js.map +2 -2
- package/dist/esm/cli/lib/typecheck.js +27 -25
- package/dist/esm/cli/lib/typecheck.js.map +2 -2
- package/dist/esm/cli/lib/usageLimits.js +129 -0
- package/dist/esm/cli/lib/usageLimits.js.map +7 -0
- package/dist/esm/cli/usageLimits.js +316 -0
- package/dist/esm/cli/usageLimits.js.map +7 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react/client.js.map +2 -2
- package/dist/esm/server/components/index.js.map +2 -2
- package/dist/esm/server/cron.js +33 -29
- package/dist/esm/server/cron.js.map +2 -2
- package/dist/esm/server/impl/database_impl.js +4 -1
- package/dist/esm/server/impl/database_impl.js.map +2 -2
- package/dist/esm/server/log.js +3 -2
- package/dist/esm/server/log.js.map +2 -2
- package/dist/esm/server/logVars.js +11 -1
- package/dist/esm/server/logVars.js.map +2 -2
- package/dist/esm/values/compare.js +5 -1
- package/dist/esm/values/compare.js.map +2 -2
- package/dist/esm/values/index.js +1 -1
- package/dist/esm/values/index.js.map +2 -2
- package/dist/esm/values/size.js +4 -0
- package/dist/esm/values/size.js.map +2 -2
- package/dist/esm/values/validator.js +12 -0
- package/dist/esm/values/validator.js.map +2 -2
- package/dist/esm/values/validators.js +19 -0
- package/dist/esm/values/validators.js.map +2 -2
- package/dist/esm/values/value.js +29 -1
- package/dist/esm/values/value.js.map +2 -2
- package/dist/esm-types/browser/index.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/paginated_query_client.d.ts +1 -38
- package/dist/esm-types/browser/sync/paginated_query_client.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen_templates/component_api.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen_templates/validator_helpers.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen_templates/validator_helpers.test.d.ts +2 -0
- package/dist/esm-types/cli/codegen_templates/validator_helpers.test.d.ts.map +1 -0
- package/dist/esm-types/cli/deployment.d.ts.map +1 -1
- package/dist/esm-types/cli/deploymentCreate.d.ts +2 -2
- package/dist/esm-types/cli/generatedApi.d.ts +43 -43
- package/dist/esm-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deployApi/validator.d.ts +6 -0
- package/dist/esm-types/cli/lib/deployApi/validator.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deploymentSelection.d.ts +2 -2
- package/dist/esm-types/cli/lib/deploymentSelection.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts +45 -45
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/projectMismatch.d.ts +2 -2
- package/dist/esm-types/cli/lib/localDeployment/projectMismatch.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/login.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/mcp/tools/insights.d.ts +24 -24
- package/dist/esm-types/cli/lib/typecheck.d.ts +2 -0
- package/dist/esm-types/cli/lib/typecheck.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/typecheck.test.d.ts +2 -0
- package/dist/esm-types/cli/lib/typecheck.test.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/usageLimits.d.ts +46 -0
- package/dist/esm-types/cli/lib/usageLimits.d.ts.map +1 -0
- package/dist/esm-types/cli/usageLimits.d.ts +22 -0
- package/dist/esm-types/cli/usageLimits.d.ts.map +1 -0
- package/dist/esm-types/index.d.ts +1 -1
- package/dist/esm-types/index.d.ts.map +1 -1
- package/dist/esm-types/react/client.d.ts.map +1 -1
- package/dist/esm-types/server/components/index.d.ts +26 -8
- package/dist/esm-types/server/components/index.d.ts.map +1 -1
- package/dist/esm-types/server/cron.d.ts +20 -11
- package/dist/esm-types/server/cron.d.ts.map +1 -1
- package/dist/esm-types/server/cron.test.d.ts +2 -0
- package/dist/esm-types/server/cron.test.d.ts.map +1 -0
- package/dist/esm-types/server/database.d.ts.map +1 -1
- package/dist/esm-types/server/impl/database_impl.d.ts.map +1 -1
- package/dist/esm-types/server/log.d.ts.map +1 -1
- package/dist/esm-types/server/logVars.d.ts +14 -1
- package/dist/esm-types/server/logVars.d.ts.map +1 -1
- package/dist/esm-types/server/meta.d.ts +2 -2
- package/dist/esm-types/server/meta.d.ts.map +1 -1
- package/dist/esm-types/values/compare.d.ts.map +1 -1
- package/dist/esm-types/values/index.d.ts +2 -2
- package/dist/esm-types/values/index.d.ts.map +1 -1
- package/dist/esm-types/values/size.d.ts +1 -1
- package/dist/esm-types/values/size.d.ts.map +1 -1
- package/dist/esm-types/values/validator.d.ts +10 -1
- package/dist/esm-types/values/validator.d.ts.map +1 -1
- package/dist/esm-types/values/validators.d.ts +14 -3
- package/dist/esm-types/values/validators.d.ts.map +1 -1
- package/dist/esm-types/values/value.d.ts +18 -1
- package/dist/esm-types/values/value.d.ts.map +1 -1
- package/dist/react.bundle.js +53 -11
- package/dist/react.bundle.js.map +2 -2
- package/package.json +8 -8
- package/schemas/convex.schema.json +2 -1
- package/src/browser/index.ts +2 -0
- package/src/browser/sync/client.test.ts +8 -1
- package/src/browser/sync/client.ts +63 -0
- package/src/browser/sync/paginated_query_client.test.ts +209 -1
- package/src/browser/sync/paginated_query_client.ts +29 -11
- package/src/cli/codegen_templates/component_api.ts +8 -3
- package/src/cli/codegen_templates/validator_helpers.test.ts +31 -0
- package/src/cli/codegen_templates/validator_helpers.ts +6 -0
- package/src/cli/deployment.ts +4 -1
- package/src/cli/deploymentCreate.test.ts +2 -2
- package/src/cli/deploymentCreate.ts +2 -2
- package/src/cli/generatedApi.ts +43 -43
- package/src/cli/lib/deployApi/validator.ts +1 -0
- package/src/cli/lib/deploymentSelection.ts +2 -2
- package/src/cli/lib/generateDocs.test.ts +1 -1
- package/src/cli/lib/generateDocs.ts +3 -3
- package/src/cli/lib/generatedFunctionLogsApi.ts +45 -45
- package/src/cli/lib/localDeployment/projectMismatch.ts +2 -2
- package/src/cli/lib/login.ts +33 -30
- package/src/cli/lib/typecheck.test.ts +71 -0
- package/src/cli/lib/typecheck.ts +33 -27
- package/src/cli/lib/usageLimits.ts +242 -0
- package/src/cli/usageLimits.ts +420 -0
- package/src/index.ts +1 -1
- package/src/react/ConvexAuthState.test.tsx +24 -8
- package/src/react/auth_websocket.test.tsx +39 -29
- package/src/react/client.ts +3 -2
- package/src/react/client_provided_base_client.test.tsx +154 -36
- package/src/server/audit_logging.test.ts +2 -0
- package/src/server/components/index.test.ts +33 -1
- package/src/server/components/index.ts +41 -14
- package/src/server/cron.test.ts +58 -0
- package/src/server/cron.ts +82 -21
- package/src/server/database.ts +17 -0
- package/src/server/impl/database_impl.ts +4 -1
- package/src/server/log.ts +4 -1
- package/src/server/logVars.ts +17 -1
- package/src/server/meta.ts +2 -2
- package/src/server/schema.test.ts +6 -1
- package/src/values/compare.ts +5 -2
- package/src/values/index.ts +2 -1
- package/src/values/size.test.ts +5 -0
- package/src/values/size.ts +5 -1
- package/src/values/validator.test.ts +16 -1
- package/src/values/validator.ts +13 -0
- package/src/values/validators.ts +29 -1
- package/src/values/value.test.ts +35 -0
- package/src/values/value.ts +56 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/react/client.ts"],
|
|
4
|
-
"sourcesContent": ["import { BaseConvexClient } from \"../browser/index.js\";\nimport type {\n OptimisticUpdate,\n PaginatedQueryToken,\n QueryToken,\n PaginationStatus,\n} from \"../browser/index.js\";\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport { convexToJson, Value } from \"../values/index.js\";\nimport { QueryJournal } from \"../browser/sync/protocol.js\";\nimport {\n AuthTokenFetcher,\n BaseConvexClientOptions,\n ConnectionState,\n} from \"../browser/sync/client.js\";\nimport type { UserIdentityAttributes } from \"../browser/sync/protocol.js\";\nimport { RequestForQueries, useQueries } from \"./use_queries.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n makeFunctionReference,\n} from \"../server/api.js\";\nimport { EmptyObject } from \"../server/registration.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n Logger,\n} from \"../browser/logging.js\";\nimport type { QueryOptions } from \"../browser/query_options.js\";\nimport { LoadMoreOfPaginatedQuery } from \"../browser/sync/pagination.js\";\nimport {\n PaginatedQueryClient,\n ExtendedTransition,\n} from \"../browser/sync/paginated_query_client.js\";\n\n// When no arguments are passed, extend subscriptions (for APIs that do this by default)\n// for this amount after the subscription would otherwise be dropped.\nconst DEFAULT_EXTEND_SUBSCRIPTION_FOR = 5_000;\n\nif (typeof React === \"undefined\") {\n throw new Error(\"Required dependency 'react' not found\");\n}\n\n// TODO Typedoc doesn't generate documentation for the comment below perhaps\n// because it's a callable interface.\n/**\n * An interface to execute a Convex mutation function on the server.\n *\n * @public\n */\nexport interface ReactMutation<Mutation extends FunctionReference<\"mutation\">> {\n /**\n * Execute the mutation on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the mutation to pass up to the server.\n * @returns The return value of the server-side function call.\n */\n (...args: OptionalRestArgs<Mutation>): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Define an optimistic update to apply as part of this mutation.\n *\n * This is a temporary update to the local query results to facilitate a\n * fast, interactive UI. It enables query results to update before a mutation\n * executed on the server.\n *\n * When the mutation is invoked, the optimistic update will be applied.\n *\n * Optimistic updates can also be used to temporarily remove queries from the\n * client and create loading experiences until a mutation completes and the\n * new query results are synced.\n *\n * The update will be automatically rolled back when the mutation is fully\n * completed and queries have been updated.\n *\n * @param optimisticUpdate - The optimistic update to apply.\n * @returns A new `ReactMutation` with the update configured.\n *\n * @public\n */\n withOptimisticUpdate<T extends OptimisticUpdate<FunctionArgs<Mutation>>>(\n optimisticUpdate: T &\n (ReturnType<T> extends Promise<any>\n ? \"Optimistic update handlers must be synchronous\"\n : {}),\n ): ReactMutation<Mutation>;\n}\n\n// Exported only for testing.\nexport function createMutation(\n mutationReference: FunctionReference<\"mutation\">,\n client: ConvexReactClient,\n update?: OptimisticUpdate<any>,\n): ReactMutation<any> {\n function mutation(args?: Record<string, Value>): Promise<unknown> {\n assertNotAccidentalArgument(args);\n\n return client.mutation(mutationReference, args, {\n optimisticUpdate: update,\n });\n }\n mutation.withOptimisticUpdate = function withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<any>,\n ): ReactMutation<any> {\n if (update !== undefined) {\n throw new Error(\n `Already specified optimistic update for mutation ${getFunctionName(\n mutationReference,\n )}`,\n );\n }\n return createMutation(mutationReference, client, optimisticUpdate);\n };\n return mutation as ReactMutation<any>;\n}\n\n/**\n * An interface to execute a Convex action on the server.\n *\n * @public\n */\nexport interface ReactAction<Action extends FunctionReference<\"action\">> {\n /**\n * Execute the function on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the function to pass up to the server.\n * @returns The return value of the server-side function call.\n * @public\n */\n (...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;\n}\n\nfunction createAction(\n actionReference: FunctionReference<\"action\">,\n client: ConvexReactClient,\n): ReactAction<any> {\n return function (args?: Record<string, Value>): Promise<unknown> {\n return client.action(actionReference, args);\n } as ReactAction<any>;\n}\n\n// Watches should be stateless: in QueriesObserver we create a watch just to get\n// the current value.\n/**\n * A watch on the output of a Convex query function.\n *\n * @public\n */\nexport interface Watch<T> {\n /**\n * Initiate a watch on the output of a query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * **Important: If the client is already subscribed to this query with the\n * same arguments this callback will not be invoked until the query result is\n * updated.** To get the current, local result call\n * {@link react.Watch.localQueryResult}.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a query.\n *\n * This will only return a result if we're already subscribed to the query\n * and have received a result from the server or the query value has been set\n * optimistically.\n *\n * @returns The result of the query or `undefined` if it isn't known.\n * @throws An error if the query encountered an error on the server.\n */\n localQueryResult(): T | undefined;\n\n /**\n * @internal\n */\n localQueryLogs(): string[] | undefined;\n\n /**\n * Get the current {@link browser.QueryJournal} for this query.\n *\n * If we have not yet received a result for this query, this will be `undefined`.\n */\n journal(): QueryJournal | undefined;\n}\n\n/**\n * A watch on the output of a paginated Convex query function.\n *\n * @public\n */\nexport interface PaginatedWatch<T> {\n /**\n * Initiate a watch on the output of a paginated query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a paginated query.\n *\n * @returns The current results, status, and loadMore function, or `undefined` if not loaded.\n */\n localQueryResult():\n | {\n results: T[];\n status: PaginationStatus;\n loadMore: LoadMoreOfPaginatedQuery;\n }\n | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchQuery}.\n *\n * @public\n */\nexport interface WatchQueryOptions {\n /**\n * An (optional) journal produced from a previous execution of this query\n * function.\n *\n * If there is an existing subscription to a query function with the same\n * name and arguments, this journal will have no effect.\n */\n journal?: QueryJournal;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchPaginatedQuery}.\n *\n * @internal\n */\nexport interface WatchPaginatedQueryOptions {\n /**\n * The initial number of items to load.\n */\n initialNumItems: number;\n\n // We may be able to remove this in the future, but to preserve the existing behavior of\n // usePaginatedQuery() it's still here.\n id: number;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.mutation}.\n *\n * @public\n */\nexport interface MutationOptions<Args extends Record<string, Value>> {\n /**\n * An optimistic update to apply along with this mutation.\n *\n * An optimistic update locally updates queries while a mutation is pending.\n * Once the mutation completes, the update will be rolled back.\n */\n optimisticUpdate?: OptimisticUpdate<Args> | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient}.\n *\n * @public\n */\nexport interface ConvexReactClientOptions extends BaseConvexClientOptions {\n /**\n * An already-constructed {@link BaseConvexClient} to use instead of\n * constructing one internally. When provided, this client (and its\n * derived {@link PaginatedQueryClient}) is used for all operations.\n *\n * @internal\n */\n baseClient?: BaseConvexClient;\n\n // FIXME: Ideally we define `ConvexReactClientOptions` as\n // `type ConvexReactClientOptions = BaseConvexClientOptions | { baseClient: BaseConvexClient }`\n // so that callers won\u2019t try to set `BaseConvexClientOptions` attributes that are ineffective.\n // But since `baseClient` is internal at the moment, I don\u2019t think we can do that.\n // We can fix this if we ever make `baseClient` public.\n}\n\n/**\n * A Convex client for use within React.\n *\n * This loads reactive queries and executes mutations over a WebSocket.\n *\n * @public\n */\nexport class ConvexReactClient {\n private address: string;\n private cachedSync?: BaseConvexClient | undefined;\n private cachedPaginatedQueryClient?: PaginatedQueryClient | undefined;\n private listeners: Map<QueryToken | PaginatedQueryToken, Set<() => void>>;\n private options: ConvexReactClientOptions;\n // \"closed\" means this client is done, not just that the underlying WS connection is closed.\n private closed = false;\n private _logger: Logger;\n\n private adminAuth?: string;\n private fakeUserIdentity?: UserIdentityAttributes | undefined;\n\n /**\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - See {@link ConvexReactClientOptions} for a full description.\n */\n constructor(address: string, options?: ConvexReactClientOptions) {\n // Validate address immediately since validation by the lazily-instantiated\n // internal client does not occur synchronously.\n if (address === undefined) {\n throw new Error(\n \"No address provided to ConvexReactClient.\\n\" +\n \"If trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\\n\" +\n \"If running locally, make sure to run `convex dev` and ensure the .env.local file is populated.\",\n );\n }\n if (typeof address !== \"string\") {\n throw new Error(\n `ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof address} instead.`,\n );\n }\n if (!address.includes(\"://\")) {\n throw new Error(\"Provided address was not an absolute URL.\");\n }\n this.address = address;\n this.listeners = new Map();\n this._logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: options?.verbose ?? false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: options?.verbose ?? false });\n this.options = { ...options, logger: this._logger };\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Lazily instantiate the `BaseConvexClient` so we don't create the WebSocket\n * when server-side rendering.\n *\n * @internal\n */\n get sync() {\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n return this.cachedSync;\n }\n // BaseConvexClient and paginated query client are always created together.\n this.cachedSync =\n this.options.baseClient ??\n new BaseConvexClient(\n this.address,\n () => {}, // Use the PaginatedQueryClient's transition instead.\n this.options,\n );\n if (this.adminAuth) {\n this.cachedSync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);\n }\n this.cachedPaginatedQueryClient = new PaginatedQueryClient(\n this.cachedSync,\n (transition) => this.handleTransition(transition),\n );\n return this.cachedSync;\n }\n\n /**\n * Lazily instantiate the `PaginatedQueryClient` so we don't create it\n * when server-side rendering.\n *\n * @internal\n */\n get paginatedQueryClient() {\n // access sync to instantiate the clients\n this.sync;\n if (this.cachedPaginatedQueryClient) {\n return this.cachedPaginatedQueryClient;\n }\n throw new Error(\"Should already be instantiated\");\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n * @param onChange - a callback that will be called when the authentication status changes\n * @param onRefreshChange - a callback called with `true` when the socket is paused to fetch a replacement token after a server rejection, and `false` when refresh completes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n onRefreshChange?: (isRefreshing: boolean) => void,\n ) {\n if (typeof fetchToken === \"string\") {\n throw new Error(\n \"Passing a string to ConvexReactClient.setAuth is no longer supported, \" +\n \"please upgrade to passing in an async function to handle reauthentication.\",\n );\n }\n this.sync.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n onRefreshChange,\n );\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.sync.clearAuth();\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n this.adminAuth = token;\n this.fakeUserIdentity = identity;\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n this.sync.setAdminAuth(token, identity);\n }\n }\n\n /**\n * Construct a new {@link Watch} on a Convex query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link useQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchQueryOptions} options object for this query.\n *\n * @returns The {@link Watch} object.\n */\n watchQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...argsAndOptions: ArgsAndOptions<Query, WatchQueryOptions>\n ): Watch<FunctionReturnType<Query>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { queryToken, unsubscribe } = this.sync.subscribe(\n name as string,\n args,\n options,\n );\n\n const currentListeners = this.listeners.get(queryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(queryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(queryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(queryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use the cached client because we can't have a query result if we don't\n // even have a client yet!\n if (this.cachedSync) {\n return this.cachedSync.localQueryResult(name, args);\n }\n return undefined;\n },\n\n localQueryLogs: () => {\n if (this.cachedSync) {\n return this.cachedSync.localQueryLogs(name, args);\n }\n return undefined;\n },\n\n journal: () => {\n if (this.cachedSync) {\n return this.cachedSync.queryJournal(name, args);\n }\n return undefined;\n },\n };\n }\n\n // Let's try out a queryOptions-style API.\n // This method is similar to the React Query API `queryClient.prefetchQuery()`.\n // In the future an ensureQueryData(): Promise<Data> method could exist.\n /**\n * Indicates likely future interest in a query subscription.\n *\n * The implementation currently immediately subscribes to a query. In the future this method\n * may prioritize some queries over others, fetch the query result without subscribing, or\n * do nothing in slow network connections or high load scenarios.\n *\n * To use this in a React component, call useQuery() and ignore the return value.\n *\n * @param queryOptions - A query (function reference from an api object) and its args, plus\n * an optional extendSubscriptionFor for how long to subscribe to the query.\n */\n prewarmQuery<Query extends FunctionReference<\"query\">>(\n queryOptions: QueryOptions<Query> & { extendSubscriptionFor?: number },\n ) {\n const extendSubscriptionFor =\n queryOptions.extendSubscriptionFor ?? DEFAULT_EXTEND_SUBSCRIPTION_FOR;\n const watch = this.watchQuery(queryOptions.query, queryOptions.args || {});\n const unsubscribe = watch.onUpdate(() => {});\n setTimeout(unsubscribe, extendSubscriptionFor);\n }\n\n /**\n * Construct a new {@link PaginatedWatch} on a Convex paginated query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link usePaginatedQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchPaginatedQueryOptions} options object for this query.\n *\n * @returns The {@link PaginatedWatch} object.\n *\n * @internal\n */\n watchPaginatedQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n options: WatchPaginatedQueryOptions,\n ): PaginatedWatch<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { paginatedQueryToken, unsubscribe } =\n this.paginatedQueryClient.subscribe(name, args || {}, options);\n\n const currentListeners = this.listeners.get(paginatedQueryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(paginatedQueryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(paginatedQueryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(paginatedQueryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use our new paginated query client\n return this.paginatedQueryClient.localQueryResult(name, args, options);\n },\n };\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...argsAndOptions: ArgsAndOptions<\n Mutation,\n MutationOptions<FunctionArgs<Mutation>>\n >\n ): Promise<FunctionReturnType<Mutation>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(mutation);\n return this.sync.mutation(name, args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const name = getFunctionName(action);\n return this.sync.action(name, ...args);\n }\n\n /**\n * Fetch a query result once.\n *\n * **Most application code should subscribe to queries instead, using\n * the {@link useQuery} hook.**\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const watch = this.watchQuery(query, ...args);\n const existingResult = watch.localQueryResult();\n if (existingResult !== undefined) {\n return Promise.resolve(existingResult);\n }\n return new Promise((resolve, reject) => {\n const unsubscribe = watch.onUpdate(() => {\n unsubscribe();\n try {\n resolve(watch.localQueryResult());\n } catch (e) {\n reject(e);\n }\n });\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n return this.sync.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n * ConnectionState may also *lose* properties in future versions as we figure\n * out what information is most useful. As such this API is considered unstable.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n return this.sync.subscribeToConnectionState(cb);\n }\n\n /**\n * Get the logger for this client.\n *\n * @returns The {@link Logger} for this client.\n */\n get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Close any network handles associated with this client and stop all subscriptions.\n *\n * Call this method when you're done with a {@link ConvexReactClient} to\n * dispose of its sockets and resources.\n *\n * @returns A `Promise` fulfilled when the connection has been completely closed.\n */\n async close(): Promise<void> {\n this.closed = true;\n // Prevent outstanding React batched updates from invoking listeners.\n this.listeners = new Map();\n if (this.cachedPaginatedQueryClient) {\n this.cachedPaginatedQueryClient = undefined;\n }\n if (this.cachedSync) {\n const sync = this.cachedSync;\n this.cachedSync = undefined;\n await sync.close();\n }\n }\n\n /**\n * Handle transitions from both base client and paginated client.\n * This ensures all transitions are processed synchronously and in order.\n */\n private handleTransition(transition: ExtendedTransition) {\n const simple = transition.queries.map((q) => q.token);\n const paginated = transition.paginatedQueries.map((q) => q.token);\n this.transition([...simple, ...paginated]);\n }\n\n private transition(updatedQueries: (QueryToken | PaginatedQueryToken)[]) {\n for (const queryToken of updatedQueries) {\n const callbacks = this.listeners.get(queryToken);\n if (callbacks) {\n for (const callback of callbacks) {\n callback();\n }\n }\n }\n }\n}\n\nconst ConvexContext = React.createContext<ConvexReactClient>(\n undefined as unknown as ConvexReactClient, // in the future this will be a mocked client for testing\n);\n\n/**\n * Get the {@link ConvexReactClient} within a React component.\n *\n * This relies on the {@link ConvexProvider} being above in the React component tree.\n *\n * @returns The active {@link ConvexReactClient} object, or `undefined`.\n *\n * @public\n */\nexport function useConvex(): ConvexReactClient {\n return useContext(ConvexContext);\n}\n\n/**\n * Provides an active Convex {@link ConvexReactClient} to descendants of this component.\n *\n * Wrap your app in this component to use Convex hooks `useQuery`,\n * `useMutation`, and `useConvex`.\n *\n * @param props - an object with a `client` property that refers to a {@link ConvexReactClient}.\n *\n * @public\n */\nexport const ConvexProvider: React.FC<{\n client: ConvexReactClient;\n children?: React.ReactNode;\n}> = ({ client, children }) => {\n return React.createElement(\n ConvexContext.Provider,\n { value: client },\n children,\n );\n};\n\nexport type OptionalRestArgsOrSkip<FuncRef extends FunctionReference<any>> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject | \"skip\"]\n : [args: FuncRef[\"_args\"] | \"skip\"];\n\n/**\n * Result returned by object-form {@link useQuery_experimental}.\n *\n * @public\n */\nexport type UseQueryResult<QueryResult, ThrowOnError extends boolean = false> =\n | { status: \"pending\" }\n | { status: \"success\"; data: QueryResult }\n | (ThrowOnError extends true ? never : { status: \"error\"; error: Error });\n\ntype UseQueryOptions<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean,\n> = {\n query: Query;\n args: FunctionArgs<Query> | \"skip\";\n throwOnError?: ThrowOnError;\n};\n\n/**\n * Load a reactive query within a React component.\n *\n * This React hook subscribes to a Convex query and causes a rerender whenever\n * the query result changes. The subscription is managed automatically --\n * it starts when the component mounts and stops when it unmounts.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * // Reactively loads tasks, re-renders when data changes:\n * const tasks = useQuery(api.tasks.list, { completed: false });\n *\n * // Returns `undefined` while loading:\n * if (tasks === undefined) return <div>Loading...</div>;\n *\n * return tasks.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n *\n * // Pass \"skip\" to conditionally disable the query:\n * function MaybeProfile({ userId }: { userId?: Id<\"users\"> }) {\n * const profile = useQuery(\n * api.users.get,\n * userId ? { userId } : \"skip\",\n * );\n * // ...\n * }\n * ```\n *\n * @param query - a {@link server.FunctionReference} for the public query to run\n * like `api.dir1.dir2.filename.func`.\n * @param args - The arguments to the query function or the string `\"skip\"` if the\n * query should not be loaded.\n * @returns the result of the query. Returns `undefined` while loading.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n): Query[\"_returnType\"] | undefined {\n const skip = args[0] === \"skip\";\n const argsObject = args[0] === \"skip\" ? {} : parseArgs(args[0]);\n const queryReference =\n typeof query === \"string\"\n ? makeFunctionReference<\"query\", any, any>(query)\n : query;\n\n const queryName = getFunctionName(queryReference);\n\n const queries = useMemo(\n () =>\n skip\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n\n if (result instanceof Error) {\n throw result;\n }\n return result;\n}\n\n/**\n * Load a reactive query within a React component using an options object.\n *\n * This is an experimental form of {@link useQuery} that accepts a single\n * {@link UseQueryOptions} object instead of positional arguments.\n *\n * Consumers are expected to check the returned object `status` field to\n * make proper use of the result. If an error occurs, it will be present\n * in the result object unless `throwOnError` is `true`, in which case\n * the error will be thrown instead.\n *\n * @example\n * ```tsx\n * import { useQuery_experimental as useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * const state = useQuery({ query: api.tasks.list, args: { completed: false } });\n *\n * if (state.status === \"pending\") return <div>Loading...</div>;\n * if (state.status === \"error\") return <div>Error: {state.error.message}</div>;\n * return state.data.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n * ```\n *\n * @param options - Query options. Pass `args: \"skip\"` to disable the query.\n * @returns the current query state as a {@link UseQueryResult} object.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery_experimental<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean = false,\n>(\n options: UseQueryOptions<Query, ThrowOnError>,\n): UseQueryResult<Query[\"_returnType\"], ThrowOnError>;\n\nexport function useQuery_experimental<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean = false,\n>(\n options: UseQueryOptions<Query, ThrowOnError>,\n): UseQueryResult<Query[\"_returnType\"], false> {\n const throwOnError = options.throwOnError ?? false;\n const queryReference =\n typeof options.query === \"string\"\n ? (makeFunctionReference<\"query\", any, any>(options.query) as Query)\n : options.query;\n const skip = options.args === \"skip\";\n const argsObject = !skip\n ? parseArgs(options.args as Record<string, Value>)\n : {};\n\n const queryName = getFunctionName(queryReference);\n const queries = useMemo(\n () =>\n skip\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n\n if (result instanceof Error) {\n if (throwOnError) {\n throw result;\n }\n return {\n error: result,\n status: \"error\",\n };\n }\n\n if (result === undefined) {\n return {\n status: \"pending\",\n };\n }\n\n return {\n data: result,\n status: \"success\",\n };\n}\n\n/**\n * Construct a new {@link ReactMutation}.\n *\n * Returns a function that you can call to execute a Convex mutation. The\n * returned function is stable across renders (same reference identity), so\n * it can be safely used in dependency arrays and memoization.\n *\n * Mutations can optionally be configured with\n * [optimistic updates](https://docs.convex.dev/client/react/optimistic-updates)\n * for instant UI feedback.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function CreateTask() {\n * const createTask = useMutation(api.tasks.create);\n *\n * const handleClick = async () => {\n * await createTask({ text: \"New task\" });\n * };\n *\n * return <button onClick={handleClick}>Add Task</button>;\n * }\n * ```\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactMutation} object with that name.\n *\n * @see https://docs.convex.dev/client/react#editing-data\n * @public\n */\nexport function useMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n): ReactMutation<Mutation> {\n const mutationReference =\n typeof mutation === \"string\"\n ? makeFunctionReference<\"mutation\", any, any>(mutation)\n : mutation;\n\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useMutation` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createMutation(mutationReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(mutationReference)],\n );\n}\n\n/**\n * Construct a new {@link ReactAction}.\n *\n * Returns a function that you can call to execute a Convex action. Actions\n * can call third-party APIs and perform side effects. The returned function\n * is stable across renders (same reference identity).\n *\n * **Error handling:** Actions can fail (e.g., if an external API is down).\n * Always wrap action calls in try/catch or handle the rejected promise.\n *\n * **Note:** In most cases, calling an action directly from a client is an\n * anti-pattern. Prefer having the client call a mutation that captures the\n * user's intent (by writing to the database) and then schedules the action\n * via `ctx.scheduler.runAfter`. This ensures the intent is durably recorded\n * even if the client disconnects.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useAction } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function GenerateSummary() {\n * const generate = useAction(api.ai.generateSummary);\n *\n * const handleClick = async () => {\n * try {\n * const summary = await generate({ text: \"Some long text...\" });\n * console.log(summary);\n * } catch (error) {\n * console.error(\"Action failed:\", error);\n * }\n * };\n *\n * return <button onClick={handleClick}>Generate</button>;\n * }\n * ```\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactAction} object with that name.\n *\n * @see https://docs.convex.dev/functions/actions#calling-actions-from-clients\n * @public\n */\nexport function useAction<Action extends FunctionReference<\"action\">>(\n action: Action,\n): ReactAction<Action> {\n const convex = useContext(ConvexContext);\n const actionReference =\n typeof action === \"string\"\n ? makeFunctionReference<\"action\", any, any>(action)\n : action;\n\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useAction` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createAction(actionReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(actionReference)],\n );\n}\n\n/**\n * React hook to get the current {@link ConnectionState} and subscribe to changes.\n *\n * This hook returns the current connection state and automatically rerenders\n * when any part of the connection state changes (e.g., when going online/offline,\n * when requests start/complete, etc.).\n *\n * The shape of ConnectionState may change in the future which may cause this\n * hook to rerender more frequently.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @returns The current {@link ConnectionState} with the Convex backend.\n *\n * @public\n */\nexport function useConvexConnectionState(): ConnectionState {\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useConvexConnectionState` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n\n const getCurrentValue = useCallback(() => {\n return convex.connectionState();\n }, [convex]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n return convex.subscribeToConnectionState(() => {\n callback();\n });\n },\n [convex],\n );\n\n return useSubscription({ getCurrentValue, subscribe });\n}\n\n// When a function is called with a single argument that looks like a\n// React SyntheticEvent it was likely called as an event handler.\nfunction assertNotAccidentalArgument(value: any) {\n // these are properties of a React.SyntheticEvent\n // https://reactjs.org/docs/events.html\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"bubbles\" in value &&\n \"persist\" in value &&\n \"isDefaultPrevented\" in value\n ) {\n throw new Error(\n `Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like \\`const handler = () => myMutation();\\` and using \\`handler\\` in the event handler.`,\n );\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAiC;AAOjC,mBAAwD;AACxD,oBAAoC;
|
|
4
|
+
"sourcesContent": ["import { BaseConvexClient } from \"../browser/index.js\";\nimport type {\n OptimisticUpdate,\n PaginatedQueryToken,\n QueryToken,\n PaginationStatus,\n} from \"../browser/index.js\";\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport { convexToJson, Value } from \"../values/index.js\";\nimport { QueryJournal } from \"../browser/sync/protocol.js\";\nimport {\n AuthTokenFetcher,\n BaseConvexClientOptions,\n ConnectionState,\n BaseConvexClientInterface,\n} from \"../browser/sync/client.js\";\nimport type { UserIdentityAttributes } from \"../browser/sync/protocol.js\";\nimport { RequestForQueries, useQueries } from \"./use_queries.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n makeFunctionReference,\n} from \"../server/api.js\";\nimport { EmptyObject } from \"../server/registration.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n Logger,\n} from \"../browser/logging.js\";\nimport type { QueryOptions } from \"../browser/query_options.js\";\nimport { LoadMoreOfPaginatedQuery } from \"../browser/sync/pagination.js\";\nimport {\n PaginatedQueryClient,\n ExtendedTransition,\n} from \"../browser/sync/paginated_query_client.js\";\n\n// When no arguments are passed, extend subscriptions (for APIs that do this by default)\n// for this amount after the subscription would otherwise be dropped.\nconst DEFAULT_EXTEND_SUBSCRIPTION_FOR = 5_000;\n\nif (typeof React === \"undefined\") {\n throw new Error(\"Required dependency 'react' not found\");\n}\n\n// TODO Typedoc doesn't generate documentation for the comment below perhaps\n// because it's a callable interface.\n/**\n * An interface to execute a Convex mutation function on the server.\n *\n * @public\n */\nexport interface ReactMutation<Mutation extends FunctionReference<\"mutation\">> {\n /**\n * Execute the mutation on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the mutation to pass up to the server.\n * @returns The return value of the server-side function call.\n */\n (...args: OptionalRestArgs<Mutation>): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Define an optimistic update to apply as part of this mutation.\n *\n * This is a temporary update to the local query results to facilitate a\n * fast, interactive UI. It enables query results to update before a mutation\n * executed on the server.\n *\n * When the mutation is invoked, the optimistic update will be applied.\n *\n * Optimistic updates can also be used to temporarily remove queries from the\n * client and create loading experiences until a mutation completes and the\n * new query results are synced.\n *\n * The update will be automatically rolled back when the mutation is fully\n * completed and queries have been updated.\n *\n * @param optimisticUpdate - The optimistic update to apply.\n * @returns A new `ReactMutation` with the update configured.\n *\n * @public\n */\n withOptimisticUpdate<T extends OptimisticUpdate<FunctionArgs<Mutation>>>(\n optimisticUpdate: T &\n (ReturnType<T> extends Promise<any>\n ? \"Optimistic update handlers must be synchronous\"\n : {}),\n ): ReactMutation<Mutation>;\n}\n\n// Exported only for testing.\nexport function createMutation(\n mutationReference: FunctionReference<\"mutation\">,\n client: ConvexReactClient,\n update?: OptimisticUpdate<any>,\n): ReactMutation<any> {\n function mutation(args?: Record<string, Value>): Promise<unknown> {\n assertNotAccidentalArgument(args);\n\n return client.mutation(mutationReference, args, {\n optimisticUpdate: update,\n });\n }\n mutation.withOptimisticUpdate = function withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<any>,\n ): ReactMutation<any> {\n if (update !== undefined) {\n throw new Error(\n `Already specified optimistic update for mutation ${getFunctionName(\n mutationReference,\n )}`,\n );\n }\n return createMutation(mutationReference, client, optimisticUpdate);\n };\n return mutation as ReactMutation<any>;\n}\n\n/**\n * An interface to execute a Convex action on the server.\n *\n * @public\n */\nexport interface ReactAction<Action extends FunctionReference<\"action\">> {\n /**\n * Execute the function on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the function to pass up to the server.\n * @returns The return value of the server-side function call.\n * @public\n */\n (...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;\n}\n\nfunction createAction(\n actionReference: FunctionReference<\"action\">,\n client: ConvexReactClient,\n): ReactAction<any> {\n return function (args?: Record<string, Value>): Promise<unknown> {\n return client.action(actionReference, args);\n } as ReactAction<any>;\n}\n\n// Watches should be stateless: in QueriesObserver we create a watch just to get\n// the current value.\n/**\n * A watch on the output of a Convex query function.\n *\n * @public\n */\nexport interface Watch<T> {\n /**\n * Initiate a watch on the output of a query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * **Important: If the client is already subscribed to this query with the\n * same arguments this callback will not be invoked until the query result is\n * updated.** To get the current, local result call\n * {@link react.Watch.localQueryResult}.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a query.\n *\n * This will only return a result if we're already subscribed to the query\n * and have received a result from the server or the query value has been set\n * optimistically.\n *\n * @returns The result of the query or `undefined` if it isn't known.\n * @throws An error if the query encountered an error on the server.\n */\n localQueryResult(): T | undefined;\n\n /**\n * @internal\n */\n localQueryLogs(): string[] | undefined;\n\n /**\n * Get the current {@link browser.QueryJournal} for this query.\n *\n * If we have not yet received a result for this query, this will be `undefined`.\n */\n journal(): QueryJournal | undefined;\n}\n\n/**\n * A watch on the output of a paginated Convex query function.\n *\n * @public\n */\nexport interface PaginatedWatch<T> {\n /**\n * Initiate a watch on the output of a paginated query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a paginated query.\n *\n * @returns The current results, status, and loadMore function, or `undefined` if not loaded.\n */\n localQueryResult():\n | {\n results: T[];\n status: PaginationStatus;\n loadMore: LoadMoreOfPaginatedQuery;\n }\n | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchQuery}.\n *\n * @public\n */\nexport interface WatchQueryOptions {\n /**\n * An (optional) journal produced from a previous execution of this query\n * function.\n *\n * If there is an existing subscription to a query function with the same\n * name and arguments, this journal will have no effect.\n */\n journal?: QueryJournal;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchPaginatedQuery}.\n *\n * @internal\n */\nexport interface WatchPaginatedQueryOptions {\n /**\n * The initial number of items to load.\n */\n initialNumItems: number;\n\n // We may be able to remove this in the future, but to preserve the existing behavior of\n // usePaginatedQuery() it's still here.\n id: number;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.mutation}.\n *\n * @public\n */\nexport interface MutationOptions<Args extends Record<string, Value>> {\n /**\n * An optimistic update to apply along with this mutation.\n *\n * An optimistic update locally updates queries while a mutation is pending.\n * Once the mutation completes, the update will be rolled back.\n */\n optimisticUpdate?: OptimisticUpdate<Args> | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient}.\n *\n * @public\n */\nexport interface ConvexReactClientOptions extends BaseConvexClientOptions {\n /**\n * An already-constructed {@link BaseConvexClient} to use instead of\n * constructing one internally. When provided, this client (and its\n * derived {@link PaginatedQueryClient}) is used for all operations.\n *\n * @internal\n */\n baseClient?: BaseConvexClientInterface;\n\n // FIXME: Ideally we define `ConvexReactClientOptions` as\n // `type ConvexReactClientOptions = BaseConvexClientOptions | { baseClient: BaseConvexClient }`\n // so that callers won\u2019t try to set `BaseConvexClientOptions` attributes that are ineffective.\n // But since `baseClient` is internal at the moment, I don\u2019t think we can do that.\n // We can fix this if we ever make `baseClient` public.\n}\n\n/**\n * A Convex client for use within React.\n *\n * This loads reactive queries and executes mutations over a WebSocket.\n *\n * @public\n */\nexport class ConvexReactClient {\n private address: string;\n private cachedSync?: BaseConvexClientInterface | undefined;\n private cachedPaginatedQueryClient?: PaginatedQueryClient | undefined;\n private listeners: Map<QueryToken | PaginatedQueryToken, Set<() => void>>;\n private options: ConvexReactClientOptions;\n // \"closed\" means this client is done, not just that the underlying WS connection is closed.\n private closed = false;\n private _logger: Logger;\n\n private adminAuth?: string;\n private fakeUserIdentity?: UserIdentityAttributes | undefined;\n\n /**\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - See {@link ConvexReactClientOptions} for a full description.\n */\n constructor(address: string, options?: ConvexReactClientOptions) {\n // Validate address immediately since validation by the lazily-instantiated\n // internal client does not occur synchronously.\n if (address === undefined) {\n throw new Error(\n \"No address provided to ConvexReactClient.\\n\" +\n \"If trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\\n\" +\n \"If running locally, make sure to run `convex dev` and ensure the .env.local file is populated.\",\n );\n }\n if (typeof address !== \"string\") {\n throw new Error(\n `ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof address} instead.`,\n );\n }\n if (!address.includes(\"://\")) {\n throw new Error(\"Provided address was not an absolute URL.\");\n }\n this.address = address;\n this.listeners = new Map();\n this._logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: options?.verbose ?? false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: options?.verbose ?? false });\n this.options = { ...options, logger: this._logger };\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Lazily instantiate the `BaseConvexClient` so we don't create the WebSocket\n * when server-side rendering.\n *\n * @internal\n */\n get sync() {\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n return this.cachedSync;\n }\n // BaseConvexClient and paginated query client are always created together.\n this.cachedSync =\n this.options.baseClient ??\n new BaseConvexClient(\n this.address,\n () => {}, // Use the PaginatedQueryClient's transition instead.\n this.options,\n );\n if (this.adminAuth) {\n this.cachedSync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);\n }\n this.cachedPaginatedQueryClient = new PaginatedQueryClient(\n this.cachedSync,\n (transition) => this.handleTransition(transition),\n );\n return this.cachedSync;\n }\n\n /**\n * Lazily instantiate the `PaginatedQueryClient` so we don't create it\n * when server-side rendering.\n *\n * @internal\n */\n get paginatedQueryClient() {\n // access sync to instantiate the clients\n this.sync;\n if (this.cachedPaginatedQueryClient) {\n return this.cachedPaginatedQueryClient;\n }\n throw new Error(\"Should already be instantiated\");\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n * @param onChange - a callback that will be called when the authentication status changes\n * @param onRefreshChange - a callback called with `true` when the socket is paused to fetch a replacement token after a server rejection, and `false` when refresh completes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n onRefreshChange?: (isRefreshing: boolean) => void,\n ) {\n if (typeof fetchToken === \"string\") {\n throw new Error(\n \"Passing a string to ConvexReactClient.setAuth is no longer supported, \" +\n \"please upgrade to passing in an async function to handle reauthentication.\",\n );\n }\n this.sync.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n onRefreshChange,\n );\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.sync.clearAuth();\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n this.adminAuth = token;\n this.fakeUserIdentity = identity;\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n this.sync.setAdminAuth(token, identity);\n }\n }\n\n /**\n * Construct a new {@link Watch} on a Convex query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link useQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchQueryOptions} options object for this query.\n *\n * @returns The {@link Watch} object.\n */\n watchQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...argsAndOptions: ArgsAndOptions<Query, WatchQueryOptions>\n ): Watch<FunctionReturnType<Query>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { queryToken, unsubscribe } = this.sync.subscribe(\n name as string,\n args,\n options,\n );\n\n const currentListeners = this.listeners.get(queryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(queryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(queryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(queryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use the cached client because we can't have a query result if we don't\n // even have a client yet!\n if (this.cachedSync) {\n return this.cachedSync.localQueryResult(name, args);\n }\n return undefined;\n },\n\n localQueryLogs: () => {\n if (this.cachedSync) {\n return this.cachedSync.localQueryLogs(name, args);\n }\n return undefined;\n },\n\n journal: () => {\n if (this.cachedSync) {\n return this.cachedSync.queryJournal(name, args);\n }\n return undefined;\n },\n };\n }\n\n // Let's try out a queryOptions-style API.\n // This method is similar to the React Query API `queryClient.prefetchQuery()`.\n // In the future an ensureQueryData(): Promise<Data> method could exist.\n /**\n * Indicates likely future interest in a query subscription.\n *\n * The implementation currently immediately subscribes to a query. In the future this method\n * may prioritize some queries over others, fetch the query result without subscribing, or\n * do nothing in slow network connections or high load scenarios.\n *\n * To use this in a React component, call useQuery() and ignore the return value.\n *\n * @param queryOptions - A query (function reference from an api object) and its args, plus\n * an optional extendSubscriptionFor for how long to subscribe to the query.\n */\n prewarmQuery<Query extends FunctionReference<\"query\">>(\n queryOptions: QueryOptions<Query> & { extendSubscriptionFor?: number },\n ) {\n const extendSubscriptionFor =\n queryOptions.extendSubscriptionFor ?? DEFAULT_EXTEND_SUBSCRIPTION_FOR;\n const watch = this.watchQuery(queryOptions.query, queryOptions.args || {});\n const unsubscribe = watch.onUpdate(() => {});\n setTimeout(unsubscribe, extendSubscriptionFor);\n }\n\n /**\n * Construct a new {@link PaginatedWatch} on a Convex paginated query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link usePaginatedQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchPaginatedQueryOptions} options object for this query.\n *\n * @returns The {@link PaginatedWatch} object.\n *\n * @internal\n */\n watchPaginatedQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n options: WatchPaginatedQueryOptions,\n ): PaginatedWatch<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { paginatedQueryToken, unsubscribe } =\n this.paginatedQueryClient.subscribe(name, args || {}, options);\n\n const currentListeners = this.listeners.get(paginatedQueryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(paginatedQueryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(paginatedQueryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(paginatedQueryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use our new paginated query client\n return this.paginatedQueryClient.localQueryResult(name, args, options);\n },\n };\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...argsAndOptions: ArgsAndOptions<\n Mutation,\n MutationOptions<FunctionArgs<Mutation>>\n >\n ): Promise<FunctionReturnType<Mutation>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(mutation);\n return this.sync.mutation(name, args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const name = getFunctionName(action);\n return this.sync.action(name, ...args);\n }\n\n /**\n * Fetch a query result once.\n *\n * **Most application code should subscribe to queries instead, using\n * the {@link useQuery} hook.**\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const watch = this.watchQuery(query, ...args);\n const existingResult = watch.localQueryResult();\n if (existingResult !== undefined) {\n return Promise.resolve(existingResult);\n }\n return new Promise((resolve, reject) => {\n const unsubscribe = watch.onUpdate(() => {\n unsubscribe();\n try {\n resolve(watch.localQueryResult());\n } catch (e) {\n reject(e);\n }\n });\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n return this.sync.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n * ConnectionState may also *lose* properties in future versions as we figure\n * out what information is most useful. As such this API is considered unstable.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n return this.sync.subscribeToConnectionState(cb);\n }\n\n /**\n * Get the logger for this client.\n *\n * @returns The {@link Logger} for this client.\n */\n get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Close any network handles associated with this client and stop all subscriptions.\n *\n * Call this method when you're done with a {@link ConvexReactClient} to\n * dispose of its sockets and resources.\n *\n * @returns A `Promise` fulfilled when the connection has been completely closed.\n */\n async close(): Promise<void> {\n this.closed = true;\n // Prevent outstanding React batched updates from invoking listeners.\n this.listeners = new Map();\n if (this.cachedPaginatedQueryClient) {\n this.cachedPaginatedQueryClient = undefined;\n }\n if (this.cachedSync) {\n const sync = this.cachedSync;\n this.cachedSync = undefined;\n await sync.close();\n }\n }\n\n /**\n * Handle transitions from both base client and paginated client.\n * This ensures all transitions are processed synchronously and in order.\n */\n private handleTransition(transition: ExtendedTransition) {\n const simple = transition.queries.map((q) => q.token);\n const paginated = transition.paginatedQueries.map((q) => q.token);\n this.transition([...simple, ...paginated]);\n }\n\n private transition(updatedQueries: (QueryToken | PaginatedQueryToken)[]) {\n for (const queryToken of updatedQueries) {\n const callbacks = this.listeners.get(queryToken);\n if (callbacks) {\n for (const callback of callbacks) {\n callback();\n }\n }\n }\n }\n}\n\nconst ConvexContext = React.createContext<ConvexReactClient>(\n undefined as unknown as ConvexReactClient, // in the future this will be a mocked client for testing\n);\n\n/**\n * Get the {@link ConvexReactClient} within a React component.\n *\n * This relies on the {@link ConvexProvider} being above in the React component tree.\n *\n * @returns The active {@link ConvexReactClient} object, or `undefined`.\n *\n * @public\n */\nexport function useConvex(): ConvexReactClient {\n return useContext(ConvexContext);\n}\n\n/**\n * Provides an active Convex {@link ConvexReactClient} to descendants of this component.\n *\n * Wrap your app in this component to use Convex hooks `useQuery`,\n * `useMutation`, and `useConvex`.\n *\n * @param props - an object with a `client` property that refers to a {@link ConvexReactClient}.\n *\n * @public\n */\nexport const ConvexProvider: React.FC<{\n client: ConvexReactClient;\n children?: React.ReactNode;\n}> = ({ client, children }) => {\n return React.createElement(\n ConvexContext.Provider,\n { value: client },\n children,\n );\n};\n\nexport type OptionalRestArgsOrSkip<FuncRef extends FunctionReference<any>> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject | \"skip\"]\n : [args: FuncRef[\"_args\"] | \"skip\"];\n\n/**\n * Result returned by object-form {@link useQuery_experimental}.\n *\n * @public\n */\nexport type UseQueryResult<QueryResult, ThrowOnError extends boolean = false> =\n | { status: \"pending\" }\n | { status: \"success\"; data: QueryResult }\n | (ThrowOnError extends true ? never : { status: \"error\"; error: Error });\n\ntype UseQueryOptions<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean,\n> = {\n query: Query;\n args: FunctionArgs<Query> | \"skip\";\n throwOnError?: ThrowOnError;\n};\n\n/**\n * Load a reactive query within a React component.\n *\n * This React hook subscribes to a Convex query and causes a rerender whenever\n * the query result changes. The subscription is managed automatically --\n * it starts when the component mounts and stops when it unmounts.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * // Reactively loads tasks, re-renders when data changes:\n * const tasks = useQuery(api.tasks.list, { completed: false });\n *\n * // Returns `undefined` while loading:\n * if (tasks === undefined) return <div>Loading...</div>;\n *\n * return tasks.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n *\n * // Pass \"skip\" to conditionally disable the query:\n * function MaybeProfile({ userId }: { userId?: Id<\"users\"> }) {\n * const profile = useQuery(\n * api.users.get,\n * userId ? { userId } : \"skip\",\n * );\n * // ...\n * }\n * ```\n *\n * @param query - a {@link server.FunctionReference} for the public query to run\n * like `api.dir1.dir2.filename.func`.\n * @param args - The arguments to the query function or the string `\"skip\"` if the\n * query should not be loaded.\n * @returns the result of the query. Returns `undefined` while loading.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n): Query[\"_returnType\"] | undefined {\n const skip = args[0] === \"skip\";\n const argsObject = args[0] === \"skip\" ? {} : parseArgs(args[0]);\n const queryReference =\n typeof query === \"string\"\n ? makeFunctionReference<\"query\", any, any>(query)\n : query;\n\n const queryName = getFunctionName(queryReference);\n\n const queries = useMemo(\n () =>\n skip\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n\n if (result instanceof Error) {\n throw result;\n }\n return result;\n}\n\n/**\n * Load a reactive query within a React component using an options object.\n *\n * This is an experimental form of {@link useQuery} that accepts a single\n * {@link UseQueryOptions} object instead of positional arguments.\n *\n * Consumers are expected to check the returned object `status` field to\n * make proper use of the result. If an error occurs, it will be present\n * in the result object unless `throwOnError` is `true`, in which case\n * the error will be thrown instead.\n *\n * @example\n * ```tsx\n * import { useQuery_experimental as useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * const state = useQuery({ query: api.tasks.list, args: { completed: false } });\n *\n * if (state.status === \"pending\") return <div>Loading...</div>;\n * if (state.status === \"error\") return <div>Error: {state.error.message}</div>;\n * return state.data.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n * ```\n *\n * @param options - Query options. Pass `args: \"skip\"` to disable the query.\n * @returns the current query state as a {@link UseQueryResult} object.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery_experimental<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean = false,\n>(\n options: UseQueryOptions<Query, ThrowOnError>,\n): UseQueryResult<Query[\"_returnType\"], ThrowOnError>;\n\nexport function useQuery_experimental<\n Query extends FunctionReference<\"query\">,\n ThrowOnError extends boolean = false,\n>(\n options: UseQueryOptions<Query, ThrowOnError>,\n): UseQueryResult<Query[\"_returnType\"], false> {\n const throwOnError = options.throwOnError ?? false;\n const queryReference =\n typeof options.query === \"string\"\n ? (makeFunctionReference<\"query\", any, any>(options.query) as Query)\n : options.query;\n const skip = options.args === \"skip\";\n const argsObject = !skip\n ? parseArgs(options.args as Record<string, Value>)\n : {};\n\n const queryName = getFunctionName(queryReference);\n const queries = useMemo(\n () =>\n skip\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n\n if (result instanceof Error) {\n if (throwOnError) {\n throw result;\n }\n return {\n error: result,\n status: \"error\",\n };\n }\n\n if (result === undefined) {\n return {\n status: \"pending\",\n };\n }\n\n return {\n data: result,\n status: \"success\",\n };\n}\n\n/**\n * Construct a new {@link ReactMutation}.\n *\n * Returns a function that you can call to execute a Convex mutation. The\n * returned function is stable across renders (same reference identity), so\n * it can be safely used in dependency arrays and memoization.\n *\n * Mutations can optionally be configured with\n * [optimistic updates](https://docs.convex.dev/client/react/optimistic-updates)\n * for instant UI feedback.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function CreateTask() {\n * const createTask = useMutation(api.tasks.create);\n *\n * const handleClick = async () => {\n * await createTask({ text: \"New task\" });\n * };\n *\n * return <button onClick={handleClick}>Add Task</button>;\n * }\n * ```\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactMutation} object with that name.\n *\n * @see https://docs.convex.dev/client/react#editing-data\n * @public\n */\nexport function useMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n): ReactMutation<Mutation> {\n const mutationReference =\n typeof mutation === \"string\"\n ? makeFunctionReference<\"mutation\", any, any>(mutation)\n : mutation;\n\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useMutation` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createMutation(mutationReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(mutationReference)],\n );\n}\n\n/**\n * Construct a new {@link ReactAction}.\n *\n * Returns a function that you can call to execute a Convex action. Actions\n * can call third-party APIs and perform side effects. The returned function\n * is stable across renders (same reference identity).\n *\n * **Error handling:** Actions can fail (e.g., if an external API is down).\n * Always wrap action calls in try/catch or handle the rejected promise.\n *\n * **Note:** In most cases, calling an action directly from a client is an\n * anti-pattern. Prefer having the client call a mutation that captures the\n * user's intent (by writing to the database) and then schedules the action\n * via `ctx.scheduler.runAfter`. This ensures the intent is durably recorded\n * even if the client disconnects.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useAction } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function GenerateSummary() {\n * const generate = useAction(api.ai.generateSummary);\n *\n * const handleClick = async () => {\n * try {\n * const summary = await generate({ text: \"Some long text...\" });\n * console.log(summary);\n * } catch (error) {\n * console.error(\"Action failed:\", error);\n * }\n * };\n *\n * return <button onClick={handleClick}>Generate</button>;\n * }\n * ```\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactAction} object with that name.\n *\n * @see https://docs.convex.dev/functions/actions#calling-actions-from-clients\n * @public\n */\nexport function useAction<Action extends FunctionReference<\"action\">>(\n action: Action,\n): ReactAction<Action> {\n const convex = useContext(ConvexContext);\n const actionReference =\n typeof action === \"string\"\n ? makeFunctionReference<\"action\", any, any>(action)\n : action;\n\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useAction` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createAction(actionReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(actionReference)],\n );\n}\n\n/**\n * React hook to get the current {@link ConnectionState} and subscribe to changes.\n *\n * This hook returns the current connection state and automatically rerenders\n * when any part of the connection state changes (e.g., when going online/offline,\n * when requests start/complete, etc.).\n *\n * The shape of ConnectionState may change in the future which may cause this\n * hook to rerender more frequently.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @returns The current {@link ConnectionState} with the Convex backend.\n *\n * @public\n */\nexport function useConvexConnectionState(): ConnectionState {\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useConvexConnectionState` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n\n const getCurrentValue = useCallback(() => {\n return convex.connectionState();\n }, [convex]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n return convex.subscribeToConnectionState(() => {\n callback();\n });\n },\n [convex],\n );\n\n return useSubscription({ getCurrentValue, subscribe });\n}\n\n// When a function is called with a single argument that looks like a\n// React SyntheticEvent it was likely called as an event handler.\nfunction assertNotAccidentalArgument(value: any) {\n // these are properties of a React.SyntheticEvent\n // https://reactjs.org/docs/events.html\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"bubbles\" in value &&\n \"persist\" in value &&\n \"isDefaultPrevented\" in value\n ) {\n throw new Error(\n `Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like \\`const handler = () => myMutation();\\` and using \\`handler\\` in the event handler.`,\n );\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAiC;AAOjC,mBAAwD;AACxD,oBAAoC;AASpC,yBAA8C;AAC9C,8BAAgC;AAChC,oBAA0B;AAC1B,iBAQO;AAEP,qBAIO;AAGP,oCAGO;AAIP,MAAM,kCAAkC;AAExC,IAAI,OAAO,aAAAA,YAAU,aAAa;AAChC,QAAM,IAAI,MAAM,uCAAuC;AACzD;AAgDO,SAAS,eACd,mBACA,QACA,QACoB;AACpB,WAAS,SAAS,MAAgD;AAChE,gCAA4B,IAAI;AAEhC,WAAO,OAAO,SAAS,mBAAmB,MAAM;AAAA,MAC9C,kBAAkB;AAAA,IACpB,CAAC;AAAA,EACH;A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AAO;AAAA,IACL,MAAM,eAAe,mBAAmB,MAAM;AAAA;AAAA,IAE9C,CAAC,YAAQ,4BAAgB,iBAAiB,CAAC;AAAA,EAC7C;AACF;AAgDO,SAAS,UACd,QACqB;AACrB,QAAM,aAAS,yBAAW,aAAa;AACvC,QAAM,kBACJ,OAAO,WAAW,eACd,kCAA0C,MAAM,IAChD;AAEN,MAAI,WAAW,QAAW;AACxB,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AACA,aAAO;AAAA,IACL,MAAM,aAAa,iBAAiB,MAAM;AAAA;AAAA,IAE1C,CAAC,YAAQ,4BAAgB,eAAe,CAAC;AAAA,EAC3C;AACF;AAkBO,SAAS,2BAA4C;AAC1D,QAAM,aAAS,yBAAW,aAAa;AACvC,MAAI,WAAW,QAAW;AACxB,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AAEA,QAAM,sBAAkB,0BAAY,MAAM;AACxC,WAAO,OAAO,gBAAgB;AAAA,EAChC,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,gBAAY;AAAA,IAChB,CAAC,aAAyB;AACxB,aAAO,OAAO,2BAA2B,MAAM;AAC7C,iBAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,aAAO,yCAAgB,EAAE,iBAAiB,UAAU,CAAC;AACvD;AAIA,SAAS,4BAA4B,OAAY;AAG/C,MACE,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,aAAa,SACb,wBAAwB,OACxB;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["React", "currentListeners"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/server/components/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { PropertyValidators } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport {\n AnyFunctionReference,\n FunctionReference,\n FunctionType,\n} from \"../api.js\";\nimport { performAsyncSyscall } from \"../impl/syscall.js\";\nimport { DefaultFunctionArgs } from \"../registration.js\";\nimport {\n AppDefinitionAnalysis,\n ComponentDefinitionAnalysis,\n ComponentDefinitionType,\n} from \"./definition.js\";\nimport {\n getFunctionAddress,\n setReferencePath,\n toReferencePath,\n} from \"./paths.js\";\nimport type {\n Validator,\n VLiteral,\n VOptional,\n VString,\n VUnion,\n} from \"../../values/validators.js\";\nimport type { Infer } from \"../../values/validator.js\";\nimport { isValidator } from \"../../values/validator.js\";\nimport type { Expand } from \"../../type_utils.js\";\nexport { getFunctionAddress } from \"./paths.js\";\n\n/**\n * A serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type FunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n> = string & FunctionReference<Type, \"internal\", Args, ReturnType>;\n\n/**\n * Create a serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport async function createFunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs,\n ReturnType,\n>(\n functionReference: FunctionReference<\n Type,\n \"public\" | \"internal\",\n Args,\n ReturnType\n >,\n): Promise<FunctionHandle<Type, Args, ReturnType>> {\n const address = getFunctionAddress(functionReference);\n return await performAsyncSyscall(\"1.0/createFunctionHandle\", {\n ...address,\n version,\n });\n}\n\ninterface ComponentExports {\n [key: string]: FunctionReference<any, any, any, any> | ComponentExports;\n}\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component definition directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ComponentDefinition<\n Exports extends ComponentExports = any,\n Env extends EnvDefinition = {},\n> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any, any>>(\n definition: Definition,\n options?: UseOptions<Definition>,\n ): InstalledComponent<Definition>;\n\n /**\n * Internal type-only property tracking exports provided.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __exports: Exports;\n\n /**\n * References to this component's declared env vars. Pass one of these in\n * `app.use(child, { env: { ... } })` to bind a child's env var by\n * reference to this component's env var.\n */\n env: EnvRefFromDefinition<Env>;\n\n /**\n * Internal type-only property tracking env definition.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __env: Env;\n};\n\ntype ComponentDefinitionExports<T extends ComponentDefinition<any, any>> =\n T[\"__exports\"];\n\ntype ComponentDefinitionEnv<T extends ComponentDefinition<any, any>> =\n T[\"__env\"];\n\n/**\n * Options for installing a component via `app.use()` or `component.use()`.\n *\n * If the component declares required env vars, the `env` property is required.\n */\ntype UseOptions<Definition extends ComponentDefinition<any, any>> =\n keyof ComponentDefinitionEnv<Definition> extends never\n ? { name?: string; httpPrefix?: string }\n : {\n name?: string;\n httpPrefix?: string;\n env: UseOptionsEnv<ComponentDefinitionEnv<Definition>>;\n };\n\ntype UseOptionsEnv<E extends EnvDefinition> = Expand<\n {\n [K in keyof E as E[K] extends VOptional<any> ? never : K]:\n | Infer<E[K]>\n | EnvRef;\n } & {\n [K in keyof E as E[K] extends VOptional<any> ? K : never]?:\n | Infer<E[K]>\n | EnvRef\n | undefined;\n }\n>;\n\n/**\n * A string-like validator: `v.string()`, a string `v.literal(\"...\")`, or a\n * `v.union(...)` of those (recursively). Component env vars are serialized\n * as strings on the wire, so only string-typed validators are allowed.\n *\n * @public\n */\nexport type StringLikeValidator =\n | VString<string, \"required\">\n | VLiteral<string, \"required\">\n | VUnion<string, Validator<any, \"required\", any>[], \"required\">;\n\n/**\n * A definition of environment variables for the app.\n *\n * Maps environment variable names to string-like validators. Use\n * `v.string()` for a plain string, `v.literal(\"a\")` for an enum value, or\n * `v.union(v.literal(\"a\"), v.literal(\"b\"))` for an enum. Wrap in\n * `v.optional(...)` for optional vars.\n *\n * @example\n * ```typescript\n * import { defineApp } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * const app = defineApp({\n * env: {\n * OPENAI_API_KEY: v.string(),\n * DEBUG_MODE: v.optional(v.string()),\n * },\n * });\n * ```\n *\n * @public\n */\nexport type EnvDefinition = Record<\n string,\n StringLikeValidator | VOptional<StringLikeValidator>\n>;\n\n/**\n * Compute the typed environment object from an {@link EnvDefinition}.\n *\n * Required entries get the validator's inferred string type; optional\n * entries are `T | undefined`.\n *\n * @public\n */\nexport type EnvFromDefinition<E extends EnvDefinition> = Expand<\n {\n [K in keyof E as E[K] extends VOptional<any> ? never : K]: Infer<E[K]>;\n } & {\n [K in keyof E as E[K] extends VOptional<any> ? K : never]?:\n | Infer<E[K]>\n | undefined;\n }\n>;\n\n/**\n * A reference to a parent-declared env var, produced by `app.env.<NAME>` or\n * `component.env.<NAME>`. Pass this in `use(child, { env: { ... } })` to\n * bind a child's declared env var to the parent's env var by reference\n * instead of snapshotting its current value.\n *\n * @public\n */\nexport type EnvRef<K extends string = string> = { __envVarRef: K };\n\n/**\n * Compute the typed `env` namespace object from an {@link EnvDefinition}.\n * Each declared name maps to an {@link EnvRef} for that name.\n *\n * @public\n */\nexport type EnvRefFromDefinition<E extends EnvDefinition> = {\n [K in keyof E & string]: EnvRef<K>;\n};\n\n/**\n * Extract the typed environment from an {@link AppDefinition}.\n *\n * @public\n */\nexport type EnvFromAppDefinition<A> =\n A extends AppDefinition<infer E>\n ? EnvFromDefinition<E>\n : Record<string, never>;\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component-aware convex directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type AppDefinition<Env extends EnvDefinition = EnvDefinition> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any, any>>(\n definition: Definition,\n options?: UseOptions<Definition>,\n ): InstalledComponent<Definition>;\n\n /**\n * References to this app's declared env vars. Pass one of these in\n * `app.use(child, { env: { ... } })` to bind a child's env var by\n * reference to this app's env var.\n */\n env: EnvRefFromDefinition<Env>;\n\n /**\n * Internal type-only property tracking env definition.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __env: Env;\n};\n\ninterface ExportTree {\n // Tree with serialized `Reference`s as leaves.\n [key: string]: string | ExportTree;\n}\n\ntype CommonDefinitionData = {\n _isRoot: boolean;\n _childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][];\n _exportTree: ExportTree;\n};\n\ntype ComponentDefinitionData = CommonDefinitionData & {\n _env: PropertyValidators;\n _name: string;\n _onInitCallbacks: Record<string, (argsStr: string) => string>;\n};\ntype AppDefinitionData = CommonDefinitionData & {\n _httpPrefix?: string;\n _env?: EnvDefinition;\n};\n\n/**\n * Used to refer to an already-installed component.\n */\nclass InstalledComponent<Definition extends ComponentDefinition<any, any>> {\n /**\n * @internal\n */\n _definition: Definition;\n\n /**\n * @internal\n */\n _name: string;\n\n constructor(definition: Definition, name: string) {\n this._definition = definition;\n this._name = name;\n setReferencePath(this, `_reference/childComponent/${name}`);\n }\n\n get exports(): ComponentDefinitionExports<Definition> {\n return createExports(this._name, []);\n }\n}\n\nfunction createExports(name: string, pathParts: string[]): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createExports(name, newParts);\n } else if (prop === toReferencePath) {\n let reference = `_reference/childComponent/${name}`;\n for (const part of pathParts) {\n reference += `/${part}`;\n }\n return reference;\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction createEnvRefs(\n ownerLabel: string,\n declared: Record<string, any> | undefined,\n): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop !== \"string\") {\n return undefined;\n }\n if (!declared || !Object.prototype.hasOwnProperty.call(declared, prop)) {\n throw new Error(\n `Env var \"${prop}\" is not declared on ${ownerLabel}. Add it to the \\`env\\` option of ${ownerLabel === \"this app\" ? \"defineApp\" : \"defineComponent\"}.`,\n );\n }\n return { __envVarRef: prop };\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction isEnvRef(value: unknown): value is EnvRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EnvRef).__envVarRef === \"string\"\n );\n}\n\nfunction use<Definition extends ComponentDefinition<any, any>>(\n this: CommonDefinitionData,\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n env?: Record<string, any>;\n },\n): InstalledComponent<Definition> {\n // At runtime an imported component will have this shape.\n const importedComponentDefinition =\n definition as unknown as ImportedComponentDefinition;\n if (typeof importedComponentDefinition.componentDefinitionPath !== \"string\") {\n throw new Error(\n \"Component definition does not have the required componentDefinitionPath property. This code only works in Convex runtime.\",\n );\n }\n const name =\n options?.name ??\n // added recently\n importedComponentDefinition.defaultName ??\n // can be removed once backend is out\n importedComponentDefinition.componentDefinitionPath.split(\"/\").pop()!;\n\n if (typeof name !== \"string\") {\n throw new Error(\n `Component name must be a string. Received: ${typeof name}`,\n );\n }\n if (name.length === 0) {\n // \"\" is used internally as the name for the root component, so\n // users shouldn't try to define child components with an empty name.\n throw new Error(\"Component name cannot be empty.\");\n }\n\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined) {\n if (!httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n }\n\n const envValues: Record<string, any> = {};\n if (options?.env) {\n for (const [key, value] of Object.entries(options.env)) {\n if (value !== undefined) {\n envValues[key] = value;\n }\n }\n }\n\n this._childComponents.push([\n name,\n importedComponentDefinition,\n envValues,\n httpPrefix,\n ]);\n return new InstalledComponent(definition, name);\n}\n\n/**\n * The runtime type of a ComponentDefinition. TypeScript will claim\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ImportedComponentDefinition = {\n componentDefinitionPath: string;\n defaultName: string;\n};\n\nfunction exportAppForAnalysis(\n this: ComponentDefinition<any, any> & AppDefinitionData,\n): AppDefinitionAnalysis {\n const definitionType = { type: \"app\" as const };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n const envVars = this._env\n ? Object.entries(this._env).map(\n ([name, validator]) =>\n [\n name,\n {\n type: \"value\" as const,\n value: JSON.stringify(validator.json),\n ...(validator.isOptional === \"optional\"\n ? { optional: true }\n : {}),\n },\n ] as [string, { type: \"value\"; value: string; optional?: boolean }],\n )\n : undefined;\n return {\n definitionType,\n ...(this._httpPrefix !== undefined\n ? { httpPrefix: normalizeHttpPrefix(this._httpPrefix) }\n : {}),\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n ...(envVars !== undefined ? { envVars } : {}),\n };\n}\n\nfunction serializeExportTree(tree: ExportTree): any {\n const branch: any[] = [];\n for (const [key, child] of Object.entries(tree)) {\n let node;\n if (typeof child === \"string\") {\n node = { type: \"leaf\", leaf: child };\n } else {\n node = serializeExportTree(child);\n }\n branch.push([key, node]);\n }\n return { type: \"branch\", branch };\n}\n\nfunction normalizeHttpPrefix(prefix: string): string {\n // Ensure the prefix ends with \"/\" as required by HttpMountPath in Rust.\n return prefix.endsWith(\"/\") ? prefix : prefix + \"/\";\n}\n\nfunction buildHttpMounts(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): Record<string, string> {\n const httpMounts: Record<string, string> = {};\n for (const [name, , , httpPrefix] of childComponents) {\n if (httpPrefix !== undefined) {\n const normalized = normalizeHttpPrefix(httpPrefix);\n httpMounts[normalized] = `_reference/childComponent/${name}`;\n }\n }\n return httpMounts;\n}\n\ntype SerializedEnvArg =\n | { type: \"value\"; value: string }\n | { type: \"envVar\"; name: string };\n\nfunction serializeChildComponents(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): {\n name: string;\n path: string;\n env: [string, SerializedEnvArg][] | null;\n}[] {\n return childComponents.map(([name, definition, p]) => {\n // Note: httpPrefix (4th element) is used separately in buildHttpMounts()\n let env: [string, SerializedEnvArg][] | null = null;\n if (p !== null) {\n env = [];\n for (const [name, value] of Object.entries(p)) {\n if (value === undefined) {\n continue;\n }\n if (isEnvRef(value)) {\n env.push([name, { type: \"envVar\", name: value.__envVarRef }]);\n } else if (typeof value === \"string\") {\n env.push([name, { type: \"value\", value }]);\n } else {\n throw new Error(\n `Env var \"${name}\" must be a string or an env var reference. ` +\n `Received: ${typeof value}`,\n );\n }\n }\n }\n // we know that components carry this extra information\n const path = definition.componentDefinitionPath;\n if (!path)\n throw new Error(\n \"no .componentPath for component definition \" +\n JSON.stringify(definition, null, 2),\n );\n\n return {\n name: name!,\n path: path!,\n args: [],\n env,\n };\n });\n}\n\nfunction exportComponentForAnalysis(\n this: ComponentDefinition<any, any> & ComponentDefinitionData,\n): ComponentDefinitionAnalysis {\n const envVars = Object.entries(this._env).map(\n ([name, validator]) =>\n [\n name,\n {\n type: \"value\" as const,\n value: JSON.stringify((validator as any).json),\n ...((validator as any).isOptional === \"optional\"\n ? { optional: true }\n : {}),\n },\n ] as [string, { type: \"value\"; value: string; optional?: boolean }],\n );\n const definitionType: ComponentDefinitionType = {\n type: \"childComponent\" as const,\n name: this._name,\n args: [],\n };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n name: this._name,\n definitionType,\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n ...(envVars.length > 0 ? { envVars } : {}),\n };\n}\n\n// This is what is actually contained in a ComponentDefinition.\ntype RuntimeComponentDefinition = Omit<\n ComponentDefinition<any, any>,\n \"__exports\" | \"__env\"\n> &\n ComponentDefinitionData & {\n export: () => ComponentDefinitionAnalysis;\n };\ntype RuntimeAppDefinition = Omit<AppDefinition<any>, \"__env\"> &\n AppDefinitionData & {\n export: () => AppDefinitionAnalysis;\n };\n\n/**\n * Define a component, a piece of a Convex deployment with namespaced resources.\n *\n * Optionally define typed environment variables that will be available via\n * the `env` export from `_generated/server` in all Convex functions within\n * this component. Values are passed by the parent via\n * `app.use(component, { env: { ... } })`.\n *\n * @param name Name must be alphanumeric plus underscores. Typically these are\n * lowercase with underscores like `\"onboarding_flow_tracker\"`.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineComponent<\n Exports extends ComponentExports = any,\n const Env extends EnvDefinition = {},\n>(\n name: string,\n options?: {\n env?: Env;\n },\n): ComponentDefinition<Exports, Env> {\n const envValidators: PropertyValidators = {};\n if (options?.env) {\n for (const [key, decl] of Object.entries(options.env)) {\n if (decl !== null && decl !== undefined && isValidator(decl)) {\n envValidators[key] = decl as any;\n } else {\n throw new Error(\n `Environment variable \"${key}\" must be defined with a validator (e.g. v.string()).`,\n );\n }\n }\n }\n\n const ret: RuntimeComponentDefinition = {\n _isRoot: false,\n _name: name,\n _env: envValidators,\n _childComponents: [],\n _exportTree: {},\n _onInitCallbacks: {},\n\n env: createEnvRefs(`component \"${name}\"`, options?.env),\n\n export: exportComponentForAnalysis,\n use,\n\n ...({} as { __exports: any; __env: any }),\n };\n return ret as any as ComponentDefinition<Exports, Env>;\n}\n\n/**\n * Attach components, reuseable pieces of a Convex deployment, to this Convex app.\n *\n * Optionally define typed environment variables that will be available via\n * the `env` export from `_generated/server` in all Convex functions.\n *\n * @example\n * ```typescript\n * import { defineApp } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * const app = defineApp({\n * env: {\n * OPENAI_API_KEY: v.string(),\n * DEBUG_MODE: v.optional(v.string()),\n * },\n * });\n * export default app;\n * ```\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineApp<Env extends EnvDefinition = EnvDefinition>(options?: {\n httpPrefix?: string;\n env?: Env;\n}): AppDefinition<Env> {\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined && !httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n const env = options?.env;\n if (env !== undefined) {\n for (const [name, validator] of Object.entries(env)) {\n if (!isValidator(validator)) {\n throw new Error(\n `Environment variable \"${name}\" must be defined with a validator (e.g. v.string()).`,\n );\n }\n }\n }\n const ret: RuntimeAppDefinition = {\n _isRoot: true,\n _childComponents: [],\n _exportTree: {},\n ...(httpPrefix !== undefined ? { _httpPrefix: httpPrefix } : {}),\n ...(env !== undefined ? { _env: env } : {}),\n\n env: createEnvRefs(\"this app\", env),\n\n export: exportAppForAnalysis,\n use,\n };\n return ret as unknown as AppDefinition<Env>;\n}\n\ntype AnyInterfaceType = {\n [key: string]: AnyInterfaceType;\n} & AnyFunctionReference;\nexport type AnyComponentReference = Record<string, AnyInterfaceType>;\n\nexport type AnyChildComponents = Record<string, AnyComponentReference>;\n\n/**\n * @internal\n */\nexport function currentSystemUdfInComponent(\n componentId: string,\n): AnyComponentReference {\n return {\n [toReferencePath]: `_reference/currentSystemUdfInComponent/${componentId}`,\n };\n}\n\nfunction createChildComponents(\n root: string,\n pathParts: string[],\n): AnyChildComponents {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createChildComponents(root, newParts);\n } else if (prop === toReferencePath) {\n if (pathParts.length < 1) {\n const found = [root, ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`${root}.childComponent.functionName\\`. Found: \\`${found}\\``,\n );\n }\n return `_reference/childComponent/` + pathParts.join(\"/\");\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nexport const componentsGeneric = () => createChildComponents(\"components\", []);\n\nexport type AnyComponents = AnyChildComponents;\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,eAAwB;AAMxB,qBAAoC;AAOpC,mBAIO;AASP,uBAA4B;AAE5B,IAAAA,gBAAmC;AAkCnC,eAAsB,qBAKpB,mBAMiD;AACjD,QAAM,cAAU,iCAAmB,iBAAiB;AACpD,SAAO,UAAM,oCAAoB,4BAA4B;AAAA,IAC3D,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACH;
|
|
4
|
+
"sourcesContent": ["import { PropertyValidators } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport {\n AnyFunctionReference,\n FunctionReference,\n FunctionType,\n} from \"../api.js\";\nimport { performAsyncSyscall } from \"../impl/syscall.js\";\nimport { DefaultFunctionArgs } from \"../registration.js\";\nimport {\n AppDefinitionAnalysis,\n ComponentDefinitionAnalysis,\n ComponentDefinitionType,\n} from \"./definition.js\";\nimport {\n getFunctionAddress,\n setReferencePath,\n toReferencePath,\n} from \"./paths.js\";\nimport type {\n Validator,\n VLiteral,\n VOptional,\n VString,\n VUnion,\n} from \"../../values/validators.js\";\nimport type { Infer } from \"../../values/validator.js\";\nimport { isValidator } from \"../../values/validator.js\";\nimport type { Expand } from \"../../type_utils.js\";\nexport { getFunctionAddress } from \"./paths.js\";\n\n/**\n * A serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type FunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n> = string & FunctionReference<Type, \"internal\", Args, ReturnType>;\n\n/**\n * Create a serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport async function createFunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs,\n ReturnType,\n>(\n functionReference: FunctionReference<\n Type,\n \"public\" | \"internal\",\n Args,\n ReturnType\n >,\n): Promise<FunctionHandle<Type, Args, ReturnType>> {\n const address = getFunctionAddress(functionReference);\n return await performAsyncSyscall(\"1.0/createFunctionHandle\", {\n ...address,\n version,\n });\n}\n\ninterface ComponentExports {\n [key: string]: FunctionReference<any, any, any, any> | ComponentExports;\n}\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component definition directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ComponentDefinition<\n Exports extends ComponentExports = any,\n Env extends EnvDefinition = {},\n> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any, any>>(\n definition: Definition,\n ...args: UseArgs<Definition>\n ): InstalledComponent<Definition>;\n\n /**\n * Internal type-only property tracking exports provided.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __exports: Exports;\n\n /**\n * References to this component's declared env vars. Pass one of these in\n * `app.use(child, { env: { ... } })` to bind a child's env var by\n * reference to this component's env var.\n */\n env: EnvRefFromDefinition<Env>;\n\n /**\n * Internal type-only property tracking env definition.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __env: Env;\n};\n\ntype ComponentDefinitionExports<T extends ComponentDefinition<any, any>> =\n T[\"__exports\"];\n\ntype ComponentDefinitionEnv<T extends ComponentDefinition<any, any>> =\n T[\"__env\"];\n\n/**\n * The names in an {@link EnvDefinition} whose validators are required (not\n * wrapped in `v.optional(...)`).\n */\ntype RequiredEnvKeys<E extends EnvDefinition> = {\n [K in keyof E]: E[K] extends Validator<any, \"optional\", any> ? never : K;\n}[keyof E];\n\n/**\n * Options for installing a component via `app.use()` or `component.use()`.\n *\n * If the component declares any required env vars, the `env` property is\n * required. Otherwise it is optional, so that a component with no env vars (or\n * only optional ones) can be installed without passing `env`.\n */\ntype UseOptions<Definition extends ComponentDefinition<any, any>> =\n RequiredEnvKeys<ComponentDefinitionEnv<Definition>> extends never\n ? {\n name?: string;\n httpPrefix?: string;\n env?: UseOptionsEnv<ComponentDefinitionEnv<Definition>>;\n }\n : {\n name?: string;\n httpPrefix?: string;\n env: UseOptionsEnv<ComponentDefinitionEnv<Definition>>;\n };\n\n/**\n * The arguments to `use()` after the component definition.\n *\n * When the component declares required env vars the `options` argument is\n * mandatory (so it can't be dropped to skip the required `env`); otherwise it\n * is optional.\n */\ntype UseArgs<Definition extends ComponentDefinition<any, any>> =\n RequiredEnvKeys<ComponentDefinitionEnv<Definition>> extends never\n ? [options?: UseOptions<Definition>]\n : [options: UseOptions<Definition>];\n\ntype UseOptionsEnv<E extends EnvDefinition> = Expand<\n {\n [K in keyof E as E[K] extends Validator<any, \"optional\", any> ? never : K]:\n | Infer<E[K]>\n | EnvRef;\n } & {\n [K in keyof E as E[K] extends Validator<any, \"optional\", any>\n ? K\n : never]?: Infer<E[K]> | EnvRef | undefined;\n }\n>;\n\n/**\n * A string-like validator: `v.string()`, a string `v.literal(\"...\")`, or a\n * `v.union(...)` of those (recursively). Component env vars are serialized\n * as strings on the wire, so only string-typed validators are allowed.\n *\n * @public\n */\nexport type StringLikeValidator =\n | VString<string, \"required\">\n | VLiteral<string, \"required\">\n | VUnion<string, Validator<any, \"required\", any>[], \"required\">;\n\n/**\n * A definition of environment variables for the app.\n *\n * Maps environment variable names to string-like validators. Use\n * `v.string()` for a plain string, `v.literal(\"a\")` for an enum value, or\n * `v.union(v.literal(\"a\"), v.literal(\"b\"))` for an enum. Wrap in\n * `v.optional(...)` for optional vars.\n *\n * @example\n * ```typescript\n * import { defineApp } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * const app = defineApp({\n * env: {\n * OPENAI_API_KEY: v.string(),\n * DEBUG_MODE: v.optional(v.string()),\n * },\n * });\n * ```\n *\n * @public\n */\nexport type EnvDefinition = Record<\n string,\n StringLikeValidator | VOptional<StringLikeValidator>\n>;\n\n/**\n * Compute the typed environment object from an {@link EnvDefinition}.\n *\n * Required entries get the validator's inferred string type; optional\n * entries are `T | undefined`.\n *\n * @public\n */\nexport type EnvFromDefinition<E extends EnvDefinition> = Expand<\n {\n [K in keyof E as E[K] extends Validator<any, \"optional\", any>\n ? never\n : K]: Infer<E[K]>;\n } & {\n [K in keyof E as E[K] extends Validator<any, \"optional\", any>\n ? K\n : never]?: Infer<E[K]> | undefined;\n }\n>;\n\n/**\n * A reference to a parent-declared env var, produced by `app.env.<NAME>` or\n * `component.env.<NAME>`. Pass this in `use(child, { env: { ... } })` to\n * bind a child's declared env var to the parent's env var by reference\n * instead of snapshotting its current value.\n *\n * @public\n */\nexport type EnvRef<K extends string = string> = { __envVarRef: K };\n\n/**\n * Compute the typed `env` namespace object from an {@link EnvDefinition}.\n * Each declared name maps to an {@link EnvRef} for that name.\n *\n * @public\n */\nexport type EnvRefFromDefinition<E extends EnvDefinition> = {\n [K in keyof E & string]: EnvRef<K>;\n};\n\n/**\n * Extract the typed environment from an {@link AppDefinition}.\n *\n * @public\n */\nexport type EnvFromAppDefinition<A> =\n A extends AppDefinition<infer E>\n ? EnvFromDefinition<E>\n : Record<string, never>;\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component-aware convex directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type AppDefinition<Env extends EnvDefinition = EnvDefinition> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any, any>>(\n definition: Definition,\n ...args: UseArgs<Definition>\n ): InstalledComponent<Definition>;\n\n /**\n * References to this app's declared env vars. Pass one of these in\n * `app.use(child, { env: { ... } })` to bind a child's env var by\n * reference to this app's env var.\n */\n env: EnvRefFromDefinition<Env>;\n\n /**\n * Internal type-only property tracking env definition.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __env: Env;\n};\n\ninterface ExportTree {\n // Tree with serialized `Reference`s as leaves.\n [key: string]: string | ExportTree;\n}\n\ntype CommonDefinitionData = {\n _isRoot: boolean;\n _childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][];\n _exportTree: ExportTree;\n};\n\ntype ComponentDefinitionData = CommonDefinitionData & {\n _env: PropertyValidators;\n _name: string;\n _onInitCallbacks: Record<string, (argsStr: string) => string>;\n};\ntype AppDefinitionData = CommonDefinitionData & {\n _httpPrefix?: string;\n _env?: EnvDefinition;\n};\n\n/**\n * Used to refer to an already-installed component.\n */\nclass InstalledComponent<Definition extends ComponentDefinition<any, any>> {\n /**\n * @internal\n */\n _definition: Definition;\n\n /**\n * @internal\n */\n _name: string;\n\n constructor(definition: Definition, name: string) {\n this._definition = definition;\n this._name = name;\n setReferencePath(this, `_reference/childComponent/${name}`);\n }\n\n get exports(): ComponentDefinitionExports<Definition> {\n return createExports(this._name, []);\n }\n}\n\nfunction createExports(name: string, pathParts: string[]): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createExports(name, newParts);\n } else if (prop === toReferencePath) {\n let reference = `_reference/childComponent/${name}`;\n for (const part of pathParts) {\n reference += `/${part}`;\n }\n return reference;\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction createEnvRefs(\n ownerLabel: string,\n declared: Record<string, any> | undefined,\n): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop !== \"string\") {\n return undefined;\n }\n if (!declared || !Object.prototype.hasOwnProperty.call(declared, prop)) {\n throw new Error(\n `Env var \"${prop}\" is not declared on ${ownerLabel}. Add it to the \\`env\\` option of ${ownerLabel === \"this app\" ? \"defineApp\" : \"defineComponent\"}.`,\n );\n }\n return { __envVarRef: prop };\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction isEnvRef(value: unknown): value is EnvRef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as EnvRef).__envVarRef === \"string\"\n );\n}\n\nfunction use<Definition extends ComponentDefinition<any, any>>(\n this: CommonDefinitionData,\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n env?: Record<string, any>;\n },\n): InstalledComponent<Definition> {\n // At runtime an imported component will have this shape.\n const importedComponentDefinition =\n definition as unknown as ImportedComponentDefinition;\n if (typeof importedComponentDefinition.componentDefinitionPath !== \"string\") {\n throw new Error(\n \"Component definition does not have the required componentDefinitionPath property. This code only works in Convex runtime.\",\n );\n }\n const name =\n options?.name ??\n // added recently\n importedComponentDefinition.defaultName ??\n // can be removed once backend is out\n importedComponentDefinition.componentDefinitionPath.split(\"/\").pop()!;\n\n if (typeof name !== \"string\") {\n throw new Error(\n `Component name must be a string. Received: ${typeof name}`,\n );\n }\n if (name.length === 0) {\n // \"\" is used internally as the name for the root component, so\n // users shouldn't try to define child components with an empty name.\n throw new Error(\"Component name cannot be empty.\");\n }\n\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined) {\n if (!httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n }\n\n const envValues: Record<string, any> = {};\n if (options?.env) {\n for (const [key, value] of Object.entries(options.env)) {\n if (value !== undefined) {\n envValues[key] = value;\n }\n }\n }\n\n this._childComponents.push([\n name,\n importedComponentDefinition,\n envValues,\n httpPrefix,\n ]);\n return new InstalledComponent(definition, name);\n}\n\n/**\n * The runtime type of a ComponentDefinition. TypeScript will claim\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ImportedComponentDefinition = {\n componentDefinitionPath: string;\n defaultName: string;\n};\n\nfunction exportAppForAnalysis(\n this: ComponentDefinition<any, any> & AppDefinitionData,\n): AppDefinitionAnalysis {\n const definitionType = { type: \"app\" as const };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n const envVars = this._env\n ? Object.entries(this._env).map(\n ([name, validator]) =>\n [\n name,\n {\n type: \"value\" as const,\n value: JSON.stringify(validator.json),\n ...(validator.isOptional === \"optional\"\n ? { optional: true }\n : {}),\n },\n ] as [string, { type: \"value\"; value: string; optional?: boolean }],\n )\n : undefined;\n return {\n definitionType,\n ...(this._httpPrefix !== undefined\n ? { httpPrefix: normalizeHttpPrefix(this._httpPrefix) }\n : {}),\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n ...(envVars !== undefined ? { envVars } : {}),\n };\n}\n\nfunction serializeExportTree(tree: ExportTree): any {\n const branch: any[] = [];\n for (const [key, child] of Object.entries(tree)) {\n let node;\n if (typeof child === \"string\") {\n node = { type: \"leaf\", leaf: child };\n } else {\n node = serializeExportTree(child);\n }\n branch.push([key, node]);\n }\n return { type: \"branch\", branch };\n}\n\nfunction normalizeHttpPrefix(prefix: string): string {\n // Ensure the prefix ends with \"/\" as required by HttpMountPath in Rust.\n return prefix.endsWith(\"/\") ? prefix : prefix + \"/\";\n}\n\nfunction buildHttpMounts(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): Record<string, string> {\n const httpMounts: Record<string, string> = {};\n for (const [name, , , httpPrefix] of childComponents) {\n if (httpPrefix !== undefined) {\n const normalized = normalizeHttpPrefix(httpPrefix);\n httpMounts[normalized] = `_reference/childComponent/${name}`;\n }\n }\n return httpMounts;\n}\n\ntype SerializedEnvArg =\n | { type: \"value\"; value: string }\n | { type: \"envVar\"; name: string };\n\nfunction serializeChildComponents(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): {\n name: string;\n path: string;\n env: [string, SerializedEnvArg][] | null;\n}[] {\n return childComponents.map(([name, definition, p]) => {\n // Note: httpPrefix (4th element) is used separately in buildHttpMounts()\n let env: [string, SerializedEnvArg][] | null = null;\n if (p !== null) {\n env = [];\n for (const [name, value] of Object.entries(p)) {\n if (value === undefined) {\n continue;\n }\n if (isEnvRef(value)) {\n env.push([name, { type: \"envVar\", name: value.__envVarRef }]);\n } else if (typeof value === \"string\") {\n env.push([name, { type: \"value\", value }]);\n } else {\n throw new Error(\n `Env var \"${name}\" must be a string or an env var reference. ` +\n `Received: ${typeof value}`,\n );\n }\n }\n }\n // we know that components carry this extra information\n const path = definition.componentDefinitionPath;\n if (!path)\n throw new Error(\n \"no .componentPath for component definition \" +\n JSON.stringify(definition, null, 2),\n );\n\n return {\n name: name!,\n path: path!,\n args: [],\n env,\n };\n });\n}\n\nfunction exportComponentForAnalysis(\n this: ComponentDefinition<any, any> & ComponentDefinitionData,\n): ComponentDefinitionAnalysis {\n const envVars = Object.entries(this._env).map(\n ([name, validator]) =>\n [\n name,\n {\n type: \"value\" as const,\n value: JSON.stringify((validator as any).json),\n ...((validator as any).isOptional === \"optional\"\n ? { optional: true }\n : {}),\n },\n ] as [string, { type: \"value\"; value: string; optional?: boolean }],\n );\n const definitionType: ComponentDefinitionType = {\n type: \"childComponent\" as const,\n name: this._name,\n args: [],\n };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n name: this._name,\n definitionType,\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n ...(envVars.length > 0 ? { envVars } : {}),\n };\n}\n\n// This is what is actually contained in a ComponentDefinition.\ntype RuntimeComponentDefinition = Omit<\n ComponentDefinition<any, any>,\n \"__exports\" | \"__env\"\n> &\n ComponentDefinitionData & {\n export: () => ComponentDefinitionAnalysis;\n };\ntype RuntimeAppDefinition = Omit<AppDefinition<any>, \"__env\"> &\n AppDefinitionData & {\n export: () => AppDefinitionAnalysis;\n };\n\n/**\n * Define a component, a piece of a Convex deployment with namespaced resources.\n *\n * Optionally define typed environment variables that will be available via\n * the `env` export from `_generated/server` in all Convex functions within\n * this component. Values are passed by the parent via\n * `app.use(component, { env: { ... } })`.\n *\n * @param name Name must be alphanumeric plus underscores. Typically these are\n * lowercase with underscores like `\"onboarding_flow_tracker\"`.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineComponent<\n Exports extends ComponentExports = any,\n const Env extends EnvDefinition = {},\n>(\n name: string,\n options?: {\n env?: Env;\n },\n): ComponentDefinition<Exports, Env> {\n const envValidators: PropertyValidators = {};\n if (options?.env) {\n for (const [key, decl] of Object.entries(options.env)) {\n if (decl !== null && decl !== undefined && isValidator(decl)) {\n envValidators[key] = decl as any;\n } else {\n throw new Error(\n `Environment variable \"${key}\" must be defined with a validator (e.g. v.string()).`,\n );\n }\n }\n }\n\n const ret: RuntimeComponentDefinition = {\n _isRoot: false,\n _name: name,\n _env: envValidators,\n _childComponents: [],\n _exportTree: {},\n _onInitCallbacks: {},\n\n env: createEnvRefs(`component \"${name}\"`, options?.env),\n\n export: exportComponentForAnalysis,\n use,\n\n ...({} as { __exports: any; __env: any }),\n };\n return ret as any as ComponentDefinition<Exports, Env>;\n}\n\n/**\n * Attach components, reuseable pieces of a Convex deployment, to this Convex app.\n *\n * Optionally define typed environment variables that will be available via\n * the `env` export from `_generated/server` in all Convex functions.\n *\n * @example\n * ```typescript\n * import { defineApp } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * const app = defineApp({\n * env: {\n * OPENAI_API_KEY: v.string(),\n * DEBUG_MODE: v.optional(v.string()),\n * },\n * });\n * export default app;\n * ```\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineApp<Env extends EnvDefinition = EnvDefinition>(options?: {\n httpPrefix?: string;\n env?: Env;\n}): AppDefinition<Env> {\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined && !httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n const env = options?.env;\n if (env !== undefined) {\n for (const [name, validator] of Object.entries(env)) {\n if (!isValidator(validator)) {\n throw new Error(\n `Environment variable \"${name}\" must be defined with a validator (e.g. v.string()).`,\n );\n }\n }\n }\n const ret: RuntimeAppDefinition = {\n _isRoot: true,\n _childComponents: [],\n _exportTree: {},\n ...(httpPrefix !== undefined ? { _httpPrefix: httpPrefix } : {}),\n ...(env !== undefined ? { _env: env } : {}),\n\n env: createEnvRefs(\"this app\", env),\n\n export: exportAppForAnalysis,\n use,\n };\n return ret as unknown as AppDefinition<Env>;\n}\n\ntype AnyInterfaceType = {\n [key: string]: AnyInterfaceType;\n} & AnyFunctionReference;\nexport type AnyComponentReference = Record<string, AnyInterfaceType>;\n\nexport type AnyChildComponents = Record<string, AnyComponentReference>;\n\n/**\n * @internal\n */\nexport function currentSystemUdfInComponent(\n componentId: string,\n): AnyComponentReference {\n return {\n [toReferencePath]: `_reference/currentSystemUdfInComponent/${componentId}`,\n };\n}\n\nfunction createChildComponents(\n root: string,\n pathParts: string[],\n): AnyChildComponents {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createChildComponents(root, newParts);\n } else if (prop === toReferencePath) {\n if (pathParts.length < 1) {\n const found = [root, ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`${root}.childComponent.functionName\\`. Found: \\`${found}\\``,\n );\n }\n return `_reference/childComponent/` + pathParts.join(\"/\");\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nexport const componentsGeneric = () => createChildComponents(\"components\", []);\n\nexport type AnyComponents = AnyChildComponents;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,eAAwB;AAMxB,qBAAoC;AAOpC,mBAIO;AASP,uBAA4B;AAE5B,IAAAA,gBAAmC;AAkCnC,eAAsB,qBAKpB,mBAMiD;AACjD,QAAM,cAAU,iCAAmB,iBAAiB;AACpD,SAAO,UAAM,oCAAoB,4BAA4B;AAAA,IAC3D,GAAG;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAyQA,MAAM,mBAAqE;AAAA,EAWzE,YAAY,YAAwB,MAAc;AAPlD;AAAA;AAAA;AAAA;AAKA;AAAA;AAAA;AAAA;AAGE,SAAK,cAAc;AACnB,SAAK,QAAQ;AACb,uCAAiB,MAAM,6BAA6B,IAAI,EAAE;AAAA,EAC5D;AAAA,EAEA,IAAI,UAAkD;AACpD,WAAO,cAAc,KAAK,OAAO,CAAC,CAAC;AAAA,EACrC;AACF;AAEA,SAAS,cAAc,MAAc,WAA0B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IAAI,GAAG,MAAuB;AAC5B,UAAI,OAAO,SAAS,UAAU;AAC5B,cAAM,WAAW,CAAC,GAAG,WAAW,IAAI;AACpC,eAAO,sBAAsB,MAAM,QAAQ;AAAA,MAC7C,WAAW,SAAS,8BAAiB;AACnC,YAAI,UAAU,SAAS,GAAG;AACxB,gBAAM,QAAQ,CAAC,MAAM,GAAG,SAAS,EAAE,KAAK,GAAG;AAC3C,gBAAM,IAAI;AAAA,YACR,4CAA4C,IAAI,4CAA4C,KAAK;AAAA,UACnG;AAAA,QACF;AACA,eAAO,+BAA+B,UAAU,KAAK,GAAG;AAAA,MAC1D,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AACA,SAAO,IAAI,MAAM,CAAC,GAAG,OAAO;AAC9B;AAEO,MAAM,oBAAoB,MAAM,sBAAsB,cAAc,CAAC,CAAC;",
|
|
6
6
|
"names": ["import_paths", "name"]
|
|
7
7
|
}
|
package/dist/cjs/server/cron.js
CHANGED
|
@@ -27,6 +27,7 @@ module.exports = __toCommonJS(cron_exports);
|
|
|
27
27
|
var import_api = require("../server/api.js");
|
|
28
28
|
var import_common = require("../common/index.js");
|
|
29
29
|
var import_values = require("../values/index.js");
|
|
30
|
+
var import_paths = require("./components/paths.js");
|
|
30
31
|
const DAYS_OF_WEEK = [
|
|
31
32
|
"sunday",
|
|
32
33
|
"monday",
|
|
@@ -66,6 +67,17 @@ function validatedMinuteOfHour(n) {
|
|
|
66
67
|
}
|
|
67
68
|
return n;
|
|
68
69
|
}
|
|
70
|
+
function validatedOptionalMinuteOfHour(n) {
|
|
71
|
+
return n === void 0 ? void 0 : validatedMinuteOfHour(n);
|
|
72
|
+
}
|
|
73
|
+
function isSchedulableFunctionReference(arg) {
|
|
74
|
+
try {
|
|
75
|
+
(0, import_paths.getFunctionAddress)(arg);
|
|
76
|
+
return true;
|
|
77
|
+
} catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
69
81
|
function validatedCronString(s) {
|
|
70
82
|
return s;
|
|
71
83
|
}
|
|
@@ -133,31 +145,23 @@ class Crons {
|
|
|
133
145
|
...args
|
|
134
146
|
);
|
|
135
147
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
* @param cronIdentifier - A unique name for this scheduled job.
|
|
150
|
-
* @param schedule - What time (UTC) each day to run this function.
|
|
151
|
-
* @param functionReference - A {@link FunctionReference} for the function
|
|
152
|
-
* to schedule.
|
|
153
|
-
* @param args - The arguments to the function.
|
|
154
|
-
*/
|
|
155
|
-
hourly(cronIdentifier, schedule, functionReference, ...args) {
|
|
156
|
-
const minuteUTC = validatedMinuteOfHour(schedule.minuteUTC);
|
|
148
|
+
hourly(cronIdentifier, scheduleOrFunctionReference, functionReferenceOrArg, ...args) {
|
|
149
|
+
if (isSchedulableFunctionReference(scheduleOrFunctionReference)) {
|
|
150
|
+
this.schedule(
|
|
151
|
+
cronIdentifier,
|
|
152
|
+
{ type: "hourly" },
|
|
153
|
+
scheduleOrFunctionReference,
|
|
154
|
+
functionReferenceOrArg
|
|
155
|
+
);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const minuteUTC = validatedOptionalMinuteOfHour(
|
|
159
|
+
scheduleOrFunctionReference.minuteUTC
|
|
160
|
+
);
|
|
157
161
|
this.schedule(
|
|
158
162
|
cronIdentifier,
|
|
159
|
-
{ minuteUTC, type: "hourly" },
|
|
160
|
-
|
|
163
|
+
minuteUTC === void 0 ? { type: "hourly" } : { minuteUTC, type: "hourly" },
|
|
164
|
+
functionReferenceOrArg,
|
|
161
165
|
...args
|
|
162
166
|
);
|
|
163
167
|
}
|
|
@@ -183,10 +187,10 @@ class Crons {
|
|
|
183
187
|
*/
|
|
184
188
|
daily(cronIdentifier, schedule, functionReference, ...args) {
|
|
185
189
|
const hourUTC = validatedHourOfDay(schedule.hourUTC);
|
|
186
|
-
const minuteUTC =
|
|
190
|
+
const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);
|
|
187
191
|
this.schedule(
|
|
188
192
|
cronIdentifier,
|
|
189
|
-
{ hourUTC, minuteUTC, type: "daily" },
|
|
193
|
+
minuteUTC === void 0 ? { hourUTC, type: "daily" } : { hourUTC, minuteUTC, type: "daily" },
|
|
190
194
|
functionReference,
|
|
191
195
|
...args
|
|
192
196
|
);
|
|
@@ -214,10 +218,10 @@ class Crons {
|
|
|
214
218
|
weekly(cronIdentifier, schedule, functionReference, ...args) {
|
|
215
219
|
const dayOfWeek = validatedDayOfWeek(schedule.dayOfWeek);
|
|
216
220
|
const hourUTC = validatedHourOfDay(schedule.hourUTC);
|
|
217
|
-
const minuteUTC =
|
|
221
|
+
const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);
|
|
218
222
|
this.schedule(
|
|
219
223
|
cronIdentifier,
|
|
220
|
-
{ dayOfWeek, hourUTC, minuteUTC, type: "weekly" },
|
|
224
|
+
minuteUTC === void 0 ? { dayOfWeek, hourUTC, type: "weekly" } : { dayOfWeek, hourUTC, minuteUTC, type: "weekly" },
|
|
221
225
|
functionReference,
|
|
222
226
|
...args
|
|
223
227
|
);
|
|
@@ -249,10 +253,10 @@ class Crons {
|
|
|
249
253
|
monthly(cronIdentifier, schedule, functionReference, ...args) {
|
|
250
254
|
const day = validatedDayOfMonth(schedule.day);
|
|
251
255
|
const hourUTC = validatedHourOfDay(schedule.hourUTC);
|
|
252
|
-
const minuteUTC =
|
|
256
|
+
const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);
|
|
253
257
|
this.schedule(
|
|
254
258
|
cronIdentifier,
|
|
255
|
-
{ day, hourUTC, minuteUTC, type: "monthly" },
|
|
259
|
+
minuteUTC === void 0 ? { day, hourUTC, type: "monthly" } : { day, hourUTC, minuteUTC, type: "monthly" },
|
|
256
260
|
functionReference,
|
|
257
261
|
...args
|
|
258
262
|
);
|