convex 1.45.0 → 1.46.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 +48 -6
- package/dist/browser.bundle.js +1 -1
- package/dist/browser.bundle.js.map +2 -2
- package/dist/cjs/browser/http_client.js.map +2 -2
- package/dist/cjs/browser/query_options.js.map +2 -2
- package/dist/cjs/browser/simple_client.js.map +2 -2
- package/dist/cjs/browser/sync/optimistic_updates.js.map +1 -1
- package/dist/cjs/browser/sync/optimistic_updates_impl.js.map +2 -2
- package/dist/cjs/cli/codegen.js +2 -0
- package/dist/cjs/cli/codegen.js.map +2 -2
- package/dist/cjs/cli/deploy.js +1 -0
- package/dist/cjs/cli/deploy.js.map +2 -2
- package/dist/cjs/cli/docs.js +3 -36
- package/dist/cjs/cli/docs.js.map +2 -2
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js +101 -60
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js +107 -0
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
- package/dist/cjs/cli/lib/codegen.js.map +2 -2
- package/dist/cjs/cli/lib/components.js +12 -0
- package/dist/cjs/cli/lib/components.js.map +2 -2
- package/dist/cjs/cli/lib/deploy2.js +29 -2
- package/dist/cjs/cli/lib/deploy2.js.map +2 -2
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js +73 -0
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js.map +7 -0
- package/dist/cjs/cli/lib/deployApi/finishPush.js +1 -0
- package/dist/cjs/cli/lib/deployApi/finishPush.js.map +2 -2
- package/dist/cjs/cli/lib/deployApi/startPush.js +1 -1
- package/dist/cjs/cli/lib/deployApi/startPush.js.map +2 -2
- package/dist/cjs/cli/lib/dev.js +1 -0
- package/dist/cjs/cli/lib/dev.js.map +2 -2
- package/dist/cjs/cli/lib/generatedFunctionLogsApi.js.map +1 -1
- package/dist/cjs/cli/lib/localDeployment/run.js +30 -1
- package/dist/cjs/cli/lib/localDeployment/run.js.map +2 -2
- package/dist/cjs/cli/lib/localDeployment/upgrade.js +6 -5
- package/dist/cjs/cli/lib/localDeployment/upgrade.js.map +2 -2
- package/dist/cjs/cli/lib/localDeployment/utils.js +5 -1
- package/dist/cjs/cli/lib/localDeployment/utils.js.map +2 -2
- package/dist/cjs/cli/lib/run.js +1 -0
- package/dist/cjs/cli/lib/run.js.map +2 -2
- package/dist/cjs/cli/lib/utils/utils.js +36 -29
- package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/nextjs/index.js.map +2 -2
- package/dist/cjs/react/client.js.map +2 -2
- package/dist/cjs/react/hydration.js.map +2 -2
- package/dist/cjs/react/queries_observer.js.map +2 -2
- package/dist/cjs/react/use_paginated_query2.js.map +2 -2
- package/dist/cjs/react/use_queries.js.map +2 -2
- package/dist/cjs/server/api.js.map +2 -2
- package/dist/cjs/server/components/index.js.map +2 -2
- package/dist/cjs/server/cron.js +10 -10
- package/dist/cjs/server/cron.js.map +2 -2
- package/dist/cjs/server/impl/actions_impl.js.map +2 -2
- package/dist/cjs/server/impl/meta_impl.js +8 -2
- package/dist/cjs/server/impl/meta_impl.js.map +2 -2
- package/dist/cjs/server/impl/scheduler_impl.js.map +2 -2
- package/dist/cjs/server/index.js.map +2 -2
- package/dist/cjs/server/meta.js.map +1 -1
- package/dist/cjs/server/registration.js.map +1 -1
- package/dist/cjs/server/scheduler.js.map +1 -1
- package/dist/cjs/server/schema.js +50 -3
- package/dist/cjs/server/schema.js.map +2 -2
- package/dist/cjs/values/validator.js +1 -1
- package/dist/cjs/values/validator.js.map +2 -2
- package/dist/cjs/values/validators.js +81 -25
- package/dist/cjs/values/validators.js.map +2 -2
- package/dist/cjs-types/browser/http_client.d.ts +5 -5
- package/dist/cjs-types/browser/http_client.d.ts.map +1 -1
- package/dist/cjs-types/browser/query_options.d.ts +2 -2
- package/dist/cjs-types/browser/query_options.d.ts.map +1 -1
- package/dist/cjs-types/browser/simple_client.d.ts +6 -6
- package/dist/cjs-types/browser/simple_client.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/optimistic_updates.d.ts +4 -4
- package/dist/cjs-types/browser/sync/optimistic_updates.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/docs.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/codegen.d.ts +1 -0
- package/dist/cjs-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/components.d.ts +1 -0
- package/dist/cjs-types/cli/lib/components.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deploy2.d.ts +6 -0
- package/dist/cjs-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts +1 -2
- package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/run.d.ts +2 -0
- package/dist/cjs-types/cli/lib/localDeployment/run.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts +1 -0
- package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/run.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/utils/utils.d.ts +5 -5
- package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/cjs-types/index.d.ts +1 -1
- package/dist/cjs-types/nextjs/index.d.ts +6 -6
- package/dist/cjs-types/nextjs/index.d.ts.map +1 -1
- package/dist/cjs-types/react/client.d.ts +15 -15
- package/dist/cjs-types/react/client.d.ts.map +1 -1
- package/dist/cjs-types/react/hydration.d.ts +3 -3
- package/dist/cjs-types/react/hydration.d.ts.map +1 -1
- package/dist/cjs-types/react/queries_observer.d.ts +9 -9
- package/dist/cjs-types/react/queries_observer.d.ts.map +1 -1
- package/dist/cjs-types/react/use_paginated_query2.d.ts.map +1 -1
- package/dist/cjs-types/react/use_queries.d.ts +14 -6
- package/dist/cjs-types/react/use_queries.d.ts.map +1 -1
- package/dist/cjs-types/server/api.d.ts +157 -7
- package/dist/cjs-types/server/api.d.ts.map +1 -1
- package/dist/cjs-types/server/components/index.d.ts +2 -2
- package/dist/cjs-types/server/components/index.d.ts.map +1 -1
- package/dist/cjs-types/server/cron.d.ts +21 -20
- package/dist/cjs-types/server/cron.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/actions_impl.d.ts +4 -4
- package/dist/cjs-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/meta_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/scheduler_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/index.d.ts +1 -1
- package/dist/cjs-types/server/index.d.ts.map +1 -1
- package/dist/cjs-types/server/meta.d.ts.map +1 -1
- package/dist/cjs-types/server/registration.d.ts +7 -7
- package/dist/cjs-types/server/registration.d.ts.map +1 -1
- package/dist/cjs-types/server/scheduler.d.ts +9 -7
- package/dist/cjs-types/server/scheduler.d.ts.map +1 -1
- package/dist/cjs-types/server/schema.d.ts +1 -0
- package/dist/cjs-types/server/schema.d.ts.map +1 -1
- package/dist/cjs-types/values/validator.d.ts.map +1 -1
- package/dist/cjs-types/values/validators.d.ts +30 -0
- package/dist/cjs-types/values/validators.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +347 -133
- package/dist/cli.bundle.cjs.map +4 -4
- package/dist/esm/browser/http_client.js.map +2 -2
- package/dist/esm/browser/query_options.js.map +2 -2
- package/dist/esm/browser/simple_client.js.map +2 -2
- package/dist/esm/browser/sync/optimistic_updates_impl.js.map +2 -2
- package/dist/esm/cli/codegen.js +2 -0
- package/dist/esm/cli/codegen.js.map +2 -2
- package/dist/esm/cli/deploy.js +1 -0
- package/dist/esm/cli/deploy.js.map +2 -2
- package/dist/esm/cli/docs.js +3 -43
- package/dist/esm/cli/docs.js.map +2 -2
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js +100 -60
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js +85 -0
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
- package/dist/esm/cli/lib/codegen.js.map +2 -2
- package/dist/esm/cli/lib/components.js +12 -0
- package/dist/esm/cli/lib/components.js.map +2 -2
- package/dist/esm/cli/lib/deploy2.js +30 -2
- package/dist/esm/cli/lib/deploy2.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js +46 -0
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js.map +7 -0
- package/dist/esm/cli/lib/deployApi/finishPush.js +1 -1
- package/dist/esm/cli/lib/deployApi/finishPush.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/startPush.js +1 -1
- package/dist/esm/cli/lib/deployApi/startPush.js.map +2 -2
- package/dist/esm/cli/lib/dev.js +1 -0
- package/dist/esm/cli/lib/dev.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/run.js +30 -2
- package/dist/esm/cli/lib/localDeployment/run.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/upgrade.js +4 -3
- package/dist/esm/cli/lib/localDeployment/upgrade.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/utils.js +3 -0
- package/dist/esm/cli/lib/localDeployment/utils.js.map +2 -2
- package/dist/esm/cli/lib/run.js +1 -0
- package/dist/esm/cli/lib/run.js.map +2 -2
- package/dist/esm/cli/lib/utils/utils.js +36 -30
- package/dist/esm/cli/lib/utils/utils.js.map +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/nextjs/index.js.map +2 -2
- package/dist/esm/react/client.js.map +2 -2
- package/dist/esm/react/hydration.js +3 -1
- package/dist/esm/react/hydration.js.map +2 -2
- package/dist/esm/react/queries_observer.js +3 -1
- package/dist/esm/react/queries_observer.js.map +2 -2
- package/dist/esm/react/use_paginated_query2.js +3 -1
- package/dist/esm/react/use_paginated_query2.js.map +2 -2
- package/dist/esm/react/use_queries.js.map +2 -2
- package/dist/esm/server/api.js.map +2 -2
- package/dist/esm/server/components/index.js.map +2 -2
- package/dist/esm/server/cron.js +13 -11
- package/dist/esm/server/cron.js.map +2 -2
- package/dist/esm/server/impl/actions_impl.js.map +2 -2
- package/dist/esm/server/impl/meta_impl.js +9 -3
- package/dist/esm/server/impl/meta_impl.js.map +2 -2
- package/dist/esm/server/impl/scheduler_impl.js.map +2 -2
- package/dist/esm/server/index.js.map +2 -2
- package/dist/esm/server/schema.js +50 -3
- package/dist/esm/server/schema.js.map +2 -2
- package/dist/esm/values/validator.js +1 -1
- package/dist/esm/values/validator.js.map +2 -2
- package/dist/esm/values/validators.js +81 -25
- package/dist/esm/values/validators.js.map +2 -2
- package/dist/esm-types/browser/http_client.d.ts +5 -5
- package/dist/esm-types/browser/http_client.d.ts.map +1 -1
- package/dist/esm-types/browser/query_options.d.ts +2 -2
- package/dist/esm-types/browser/query_options.d.ts.map +1 -1
- package/dist/esm-types/browser/simple_client.d.ts +6 -6
- package/dist/esm-types/browser/simple_client.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/optimistic_updates.d.ts +4 -4
- package/dist/esm-types/browser/sync/optimistic_updates.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/docs.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/codegen.d.ts +1 -0
- package/dist/esm-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/components.d.ts +1 -0
- package/dist/esm-types/cli/lib/components.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deploy2.d.ts +6 -0
- package/dist/esm-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts +1 -2
- package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/run.d.ts +2 -0
- package/dist/esm-types/cli/lib/localDeployment/run.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/utils.d.ts +1 -0
- package/dist/esm-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/run.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/utils/utils.d.ts +5 -5
- package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/esm-types/index.d.ts +1 -1
- package/dist/esm-types/nextjs/index.d.ts +6 -6
- package/dist/esm-types/nextjs/index.d.ts.map +1 -1
- package/dist/esm-types/react/client.d.ts +15 -15
- package/dist/esm-types/react/client.d.ts.map +1 -1
- package/dist/esm-types/react/hydration.d.ts +3 -3
- package/dist/esm-types/react/hydration.d.ts.map +1 -1
- package/dist/esm-types/react/queries_observer.d.ts +9 -9
- package/dist/esm-types/react/queries_observer.d.ts.map +1 -1
- package/dist/esm-types/react/use_paginated_query2.d.ts.map +1 -1
- package/dist/esm-types/react/use_queries.d.ts +14 -6
- package/dist/esm-types/react/use_queries.d.ts.map +1 -1
- package/dist/esm-types/server/api.d.ts +157 -7
- package/dist/esm-types/server/api.d.ts.map +1 -1
- package/dist/esm-types/server/components/index.d.ts +2 -2
- package/dist/esm-types/server/components/index.d.ts.map +1 -1
- package/dist/esm-types/server/cron.d.ts +21 -20
- package/dist/esm-types/server/cron.d.ts.map +1 -1
- package/dist/esm-types/server/impl/actions_impl.d.ts +4 -4
- package/dist/esm-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/meta_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/scheduler_impl.d.ts.map +1 -1
- package/dist/esm-types/server/index.d.ts +1 -1
- package/dist/esm-types/server/index.d.ts.map +1 -1
- package/dist/esm-types/server/meta.d.ts.map +1 -1
- package/dist/esm-types/server/registration.d.ts +7 -7
- package/dist/esm-types/server/registration.d.ts.map +1 -1
- package/dist/esm-types/server/scheduler.d.ts +9 -7
- package/dist/esm-types/server/scheduler.d.ts.map +1 -1
- package/dist/esm-types/server/schema.d.ts +1 -0
- package/dist/esm-types/server/schema.d.ts.map +1 -1
- package/dist/esm-types/values/validator.d.ts.map +1 -1
- package/dist/esm-types/values/validators.d.ts +30 -0
- package/dist/esm-types/values/validators.d.ts.map +1 -1
- package/dist/react.bundle.js +1 -1
- package/dist/react.bundle.js.map +2 -2
- package/package.json +5 -5
- package/src/browser/http_client.ts +43 -10
- package/src/browser/query_options.ts +11 -5
- package/src/browser/simple_client.ts +35 -14
- package/src/browser/sync/optimistic_updates.ts +17 -4
- package/src/browser/sync/optimistic_updates_impl.ts +17 -4
- package/src/cli/codegen.ts +1 -0
- package/src/cli/deploy.ts +1 -0
- package/src/cli/docs.ts +3 -44
- package/src/cli/lib/checkForLargeIndexDeletion.ts +154 -82
- package/src/cli/lib/checkForSlowSchemaValidation.ts +130 -0
- package/src/cli/lib/codegen.ts +1 -0
- package/src/cli/lib/components.ts +17 -0
- package/src/cli/lib/deploy2.ts +56 -1
- package/src/cli/lib/deployApi/evaluateSchema.ts +62 -0
- package/src/cli/lib/deployApi/finishPush.ts +1 -1
- package/src/cli/lib/deployApi/startPush.ts +1 -1
- package/src/cli/lib/dev.ts +1 -0
- package/src/cli/lib/generatedFunctionLogsApi.ts +2 -0
- package/src/cli/lib/localDeployment/run.ts +44 -2
- package/src/cli/lib/localDeployment/upgrade.ts +4 -6
- package/src/cli/lib/localDeployment/utils.ts +6 -0
- package/src/cli/lib/run.ts +1 -0
- package/src/cli/lib/utils/utils.ts +63 -35
- package/src/index.ts +1 -1
- package/src/nextjs/index.ts +19 -8
- package/src/react/client.ts +73 -30
- package/src/react/hydration.tsx +14 -6
- package/src/react/queries_observer.ts +19 -16
- package/src/react/use_paginated_query2.ts +10 -6
- package/src/react/use_queries.ts +23 -7
- package/src/server/api.ts +220 -14
- package/src/server/components/index.ts +4 -6
- package/src/server/cron.ts +34 -24
- package/src/server/impl/actions_impl.ts +13 -4
- package/src/server/impl/meta_impl.ts +8 -1
- package/src/server/impl/scheduler_impl.ts +13 -6
- package/src/server/index.ts +1 -0
- package/src/server/meta.ts +25 -0
- package/src/server/registration.ts +28 -7
- package/src/server/scheduler.ts +22 -7
- package/src/server/schema.ts +55 -0
- package/src/values/validator.ts +3 -1
- package/src/values/validators.ts +84 -26
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/api.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _args: Args;\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference: AnyFunctionReference,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\ntype FilterKeysInApi<key, API, Predicate> = API extends Predicate\n ? key\n : API extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API, Predicate> extends Record<string, never>\n ? never\n : key;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as FilterKeysInApi<\n mod,\n API[mod],\n Predicate\n >]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * This is represented as an object mapping argument names to values.\n * @public\n */\nexport type FunctionArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FuncRef[\"_args\"]];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends AnyFunctionReference,\n Options,\n> = FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FuncRef[\"_args\"], options?: Options];\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n"],
|
|
5
|
-
"mappings": ";AAUA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * If you want to accept a `FunctionReference` as a callback argument, prefer\n * typing the callback parameter as {@link FunctionReference_future}.\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n /**\n * To read the arguments for a `FunctionReference`, prefer\n * {@link FunctionArgs}.\n *\n * This slot will be removed in a future version.\n *\n * @deprecated\n */\n _args: Args;\n /**\n * To read the return type of a `FunctionReference`, prefer\n * {@link FunctionReturnType}.\n *\n * This slot will be removed in a future version.\n *\n * @deprecated\n */\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n /**\n * To read the arguments or return type of a `FunctionReference`, prefer\n * {@link FunctionArgs} and {@link FunctionReturnType}.\n */\n // This phantom slot exists so that a `FunctionReference` can be checked\n // against a `FunctionReference_future`. It changes nothing about how two\n // `FunctionReference`s compare with each other.\n //\n // The slot models the function itself: it puts `Args` in a contravariant\n // position and `ReturnType` in a covariant one, so the slot alone is enough\n // to compare a reference the way TypeScript compares two functions.\n //\n // In that comparison the `keys` parameter has an important role. It carries\n // the keys of `Args`, so that checking a `FunctionReference` against a\n // `FunctionReference_future` also checks that every key the consumer passes\n // is a key the function declares. TypeScript treats a surplus property as\n // harmless, but a Convex argument validator rejects it, so this is what\n // makes the comparison match the runtime. See `FunctionReferenceArgKeys`.\n _fn?(args: Args, keys: FunctionReferenceArgKeys<Args>): ReturnType;\n};\n\n/**\n * The keys of a reference's arguments.\n *\n * `0 extends 1 & Args` holds only when `Args` is `any`. That maps to `any`\n * rather than `keyof any` so that an untyped reference neither imposes nor\n * fails the key check in either direction. Arguments with an index signature,\n * such as `EmptyObject` and `DefaultFunctionArgs`, map to `string`, which\n * accepts every key and leaves the decision to the first parameter.\n */\ntype ArgKeys<Args> = 0 extends 1 & Args ? any : keyof Args;\n\n/**\n * The second parameter of `FunctionReference._fn`.\n *\n * Wrapping the keys in a function of a function puts them two parameters deep,\n * so comparing this parameter contravariantly checks that every key the\n * consumer passes is one the function declares. That is the check a Convex\n * argument validator performs and an ordinary function-type comparison skips.\n *\n * The union with {@link UncheckedArgKeys} is what keeps two\n * `FunctionReference`s comparing as they did before this slot existed. Every\n * `FunctionReferenceArgKeys` is assignable to `UncheckedArgKeys`, so between\n * two `FunctionReference`s the keys always relate and only `_args` decides.\n * {@link FunctionReference_futureArgKeys} is not assignable to it, so a\n * `FunctionReference` compared against a `FunctionReference_future` has to\n * satisfy the real check.\n */\ntype FunctionReferenceArgKeys<Args> = 0 extends 1 & Args\n ? any\n : ((keys: (key: ArgKeys<Args>) => void) => void) | UncheckedArgKeys;\n\n/**\n * A keys parameter that every {@link FunctionReferenceArgKeys} is assignable\n * to, and that no {@link FunctionReference_futureArgKeys} is: `unknown` for\n * the second parameter accepts the former's missing parameter and rejects the\n * latter's `never`.\n */\ntype UncheckedArgKeys = (keys: never, unchecked?: unknown) => void;\n\n/**\n * The second parameter of `FunctionReference_future._fn`. The same shape as\n * {@link FunctionReferenceArgKeys} plus a `guard` parameter that keeps it out\n * of {@link UncheckedArgKeys}.\n */\ntype FunctionReference_futureArgKeys<Args> = 0 extends 1 & Args\n ? any\n : (keys: (key: ArgKeys<Args>) => void, guard?: never) => void;\n\n/**\n * A reference to a Convex function whose arguments are checked closer to the\n * way Convex checks them at runtime.\n *\n * Use this instead of {@link FunctionReference} when you accept someone else's\n * Convex function as a callback and know which arguments you will pass it.\n *\n * A plain `FunctionReference` gets a couple things backwards: it accepts a\n * function requiring arguments you never pass, and rejects a function\n * accepting broader values than you pass. An ordinary TypeScript function type\n * doesn't map perfectly either: it treats a surplus argument as harmless,\n * where a Convex validator rejects it.\n *\n * This type melds regular TypeScript function reference behavior with top\n * level checking of arguments to prevent surplus arguments from hitting\n * runtime validation errors. The caveat: a surplus key inside a nested object,\n * an array element, or one arm of a union passes the type check and fails the\n * validator at runtime.\n *\n * ```ts\n * import { FunctionReference_future } from \"convex/server\";\n *\n * declare function onComplete(\n * fn: FunctionReference_future<\n * \"mutation\",\n * \"internal\",\n * { taskId: string; force: boolean },\n * null\n * >,\n * ): void;\n *\n * // Takes exactly `{ taskId: string; force: boolean }`.\n * onComplete(internal.tasks.finish);\n * // Takes `{ taskId: string | number; force?: boolean }`: calling it is safe.\n * onComplete(internal.tasks.finishLoosely);\n * // Requires a `reason` argument that `onComplete` never passes.\n * onComplete(internal.tasks.finishWithReason);\n * // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rejected\n * // Takes only `{ taskId: string }`: its validator would reject `force`.\n * onComplete(internal.tasks.finishById);\n * // ~~~~~~~~~~~~~~~~~~~~~~~~ rejected\n * ```\n *\n * A value of this type is usable with `ctx.runMutation`,\n * `ctx.scheduler.runAfter`, `createFunctionHandle`, and everything else in\n * this package that takes a reference, all of which accept either kind.\n *\n * It is *not* assignable to a plain `FunctionReference`. Code that wants to\n * accept both kinds should take\n * `FunctionReference<...> | FunctionReference_future<...>` and read arguments\n * and return types through {@link FunctionArgs} and {@link FunctionReturnType}.\n *\n * Argument checking here relies on `strictFunctionTypes` (implied by `strict`)\n * and is skipped for projects that disable it. Everything else about the\n * reference is compared exactly as `FunctionReference` compares it.\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments the consumer of the reference will pass.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference_future<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _componentPath: ComponentPath;\n // Declared as a *property* rather than a method: TypeScript compares method\n // parameters bivariantly and would not check anything. The explicit\n // `| undefined` is needed because an optional method on the source side\n // (`FunctionReference._fn`) carries a real `undefined` in its type, which\n // `exactOptionalPropertyTypes` would otherwise reject.\n //\n // Both parameters are compared contravariantly: the first checks that the\n // consumer's arguments satisfy the function's, the second that the consumer\n // passes no key the function does not declare. See\n // `FunctionReference_futureArgKeys`.\n _fn?:\n | ((args: Args, keys: FunctionReference_futureArgKeys<Args>) => ReturnType)\n | undefined;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference:\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\ntype FilterKeysInApi<key, API, Predicate> = API extends Predicate\n ? key\n : API extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API, Predicate> extends Record<string, never>\n ? never\n : key;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as FilterKeysInApi<\n mod,\n API[mod],\n Predicate\n >]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference} or {@link FunctionReference_future}, get\n * the arguments of the function.\n *\n * This is represented as an object mapping argument names to values.\n *\n * @public\n */\nexport type FunctionArgs<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> = ExtractSignature<FuncRef>[\"args\"];\n\n// The arguments and return type a reference declares. A `FunctionReference`\n// declares them in `_args` and `_returnType`, a `FunctionReference_future`\n// only in its `_fn` slot. Reading the named slots first also covers a\n// reference typed by an older copy of this package, which has no `_fn`.\ntype ExtractSignature<FuncRef> = FuncRef extends {\n _args: infer Args;\n _returnType: infer R;\n}\n ? { args: Args; returnType: R }\n : FuncRef extends {\n _fn?: ((args: infer Args, keys: never) => infer R) | undefined;\n }\n ? { args: Args; returnType: R }\n : { args: any; returnType: any };\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> =\n FunctionArgs<FuncRef> extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FunctionArgs<FuncRef>];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n Options,\n> =\n FunctionArgs<FuncRef> extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FunctionArgs<FuncRef>, options?: Options];\n\n/**\n * Given a {@link FunctionReference} or {@link FunctionReference_future}, get\n * the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> = ExtractSignature<FuncRef>[\"returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n"],
|
|
5
|
+
"mappings": ";AAUA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AA+O5B,gBAAS,gBACd,mBAGQ;AACR,QAAM,UAAU,mBAAmB,iBAAiB;AAEpD,MAAI,QAAQ,SAAS,QAAW;AAC9B,QAAI,QAAQ,mBAAmB,QAAW;AACxC,YAAM,IAAI;AAAA,QACR,0GAA0G,QAAQ,cAAc;AAAA,MAClI;AAAA,IACF,WAAW,QAAQ,cAAc,QAAW;AAC1C,YAAM,IAAI;AAAA,QACR,6HAA6H,QAAQ,SAAS;AAAA,MAChJ;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR,0FAA0F,KAAK,UAAU,OAAO,CAAC;AAAA,IACnH;AAAA,EACF;AAGA,MAAI,OAAO,sBAAsB,SAAU,QAAO;AAKlD,QAAM,OAAQ,kBAA0B,YAAY;AACpD,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,GAAG,iBAAwB,6BAA6B;AAAA,EAC1E;AACA,SAAO;AACT;AAaO,gBAAS,sBAId,MAA4D;AAC5D,SAAO,EAAE,CAAC,YAAY,GAAG,KAAK;AAMhC;AAYA,SAAS,UAAU,YAAsB,CAAC,GAAW;AACnD,QAAM,UAAgC;AAAA,IACpC,IAAI,GAAG,MAAuB;AAC5B,UAAI,OAAO,SAAS,UAAU;AAC5B,cAAM,WAAW,CAAC,GAAG,WAAW,IAAI;AACpC,eAAO,UAAU,QAAQ;AAAA,MAC3B,WAAW,SAAS,cAAc;AAChC,YAAI,UAAU,SAAS,GAAG;AACxB,gBAAM,QAAQ,CAAC,OAAO,GAAG,SAAS,EAAE,KAAK,GAAG;AAC5C,gBAAM,IAAI;AAAA,YACR,oFAAoF,KAAK;AAAA,UAC3F;AAAA,QACF;AACA,cAAM,OAAO,UAAU,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG;AAC5C,cAAM,aAAa,UAAU,UAAU,SAAS,CAAC;AACjD,YAAI,eAAe,WAAW;AAC5B,iBAAO;AAAA,QACT,OAAO;AACL,iBAAO,OAAO,MAAM;AAAA,QACtB;AAAA,MACF,WAAW,SAAS,OAAO,aAAa;AACtC,eAAO;AAAA,MACT,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO,IAAI,MAAM,CAAC,GAAG,OAAO;AAC9B;AAmIO,gBAAS,UAA0B,KAAqC;AAC7E,SAAO;AACT;AAIO,gBAAS,aACd,KAC8D;AAC9D,SAAO;AACT;AAGO,gBAAS,WACd,KAC4D;AAC5D,SAAO;AACT;AAGO,gBAAS,YACd,KAC2D;AAC3D,SAAO;AACT;AAGO,gBAAS,cACd,KAC8D;AAC9D,SAAO;AACT;AAGO,gBAAS,YACd,KAC4D;AAC5D,SAAO;AACT;AAGO,gBAAS,qBACd,KASA;AACA,SAAO;AACT;AAGO,gBAAS,gBACd,KACyE;AACzE,SAAO;AACT;AAkEO,aAAM,SAAiB,UAAU;",
|
|
6
6
|
"names": []
|
|
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 ...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": ";;;;AACA,SAAS,eAAe;
|
|
4
|
+
"sourcesContent": ["import { PropertyValidators } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport {\n AnyFunctionReference,\n FunctionReference,\n FunctionReference_future,\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:\n | FunctionReference<Type, \"public\" | \"internal\", Args, ReturnType>\n | FunctionReference_future<Type, \"public\" | \"internal\", Args, ReturnType>,\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": ";;;;AACA,SAAS,eAAe;AAOxB,SAAS,2BAA2B;AAOpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AASP,SAAS,mBAAmB;AAE5B,SAAS,0BAA0B;AAkCnC,sBAAsB,qBAKpB,mBAGiD;AACjD,QAAM,UAAU,mBAAmB,iBAAiB;AACpD,SAAO,MAAM,oBAAoB,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,qBAAiB,MAAM,6BAA6B,IAAI,EAAE;AAAA,EAC5D;AA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,CAAC,eAAe,GAAG,0CAA0C,WAAW;AAAA,EAC1E;AACF;AAEA,SAAS,sBACP,MACA,WACoB;AACpB,QAAM,UAAgC;AAAA,IACpC,IAAI,GAAG,MAAuB;AAC5B,UAAI,OAAO,SAAS,UAAU;AAC5B,cAAM,WAAW,CAAC,GAAG,WAAW,IAAI;AACpC,eAAO,sBAAsB,MAAM,QAAQ;AAAA,MAC7C,WAAW,SAAS,iBAAiB;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,aAAM,oBAAoB,MAAM,sBAAsB,cAAc,CAAC,CAAC;",
|
|
6
6
|
"names": ["name"]
|
|
7
7
|
}
|
package/dist/esm/server/cron.js
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
4
4
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
getFunctionName
|
|
7
|
+
} from "../server/api.js";
|
|
6
8
|
import { parseArgs } from "../common/index.js";
|
|
7
9
|
import { convexToJson } from "../values/index.js";
|
|
8
10
|
import { getFunctionAddress } from "./components/paths.js";
|
|
@@ -96,8 +98,8 @@ export class Crons {
|
|
|
96
98
|
*
|
|
97
99
|
* @param identifier - A unique name for this scheduled job.
|
|
98
100
|
* @param schedule - The time between runs for this scheduled job.
|
|
99
|
-
* @param functionReference - A {@link FunctionReference}
|
|
100
|
-
* to schedule.
|
|
101
|
+
* @param functionReference - A {@link FunctionReference} or
|
|
102
|
+
* {@link FunctionReference_future} for the function to schedule.
|
|
101
103
|
* @param args - The arguments to the function.
|
|
102
104
|
*/
|
|
103
105
|
interval(cronIdentifier, schedule, functionReference, ...args) {
|
|
@@ -159,8 +161,8 @@ export class Crons {
|
|
|
159
161
|
*
|
|
160
162
|
* @param cronIdentifier - A unique name for this scheduled job.
|
|
161
163
|
* @param schedule - What time (UTC) each day to run this function.
|
|
162
|
-
* @param functionReference - A {@link FunctionReference}
|
|
163
|
-
* to schedule.
|
|
164
|
+
* @param functionReference - A {@link FunctionReference} or
|
|
165
|
+
* {@link FunctionReference_future} for the function to schedule.
|
|
164
166
|
* @param args - The arguments to the function.
|
|
165
167
|
*/
|
|
166
168
|
daily(cronIdentifier, schedule, functionReference, ...args) {
|
|
@@ -190,8 +192,8 @@ export class Crons {
|
|
|
190
192
|
*
|
|
191
193
|
* @param cronIdentifier - A unique name for this scheduled job.
|
|
192
194
|
* @param schedule - What day and time (UTC) each week to run this function.
|
|
193
|
-
* @param functionReference - A {@link FunctionReference}
|
|
194
|
-
* to schedule.
|
|
195
|
+
* @param functionReference - A {@link FunctionReference} or
|
|
196
|
+
* {@link FunctionReference_future} for the function to schedule.
|
|
195
197
|
*/
|
|
196
198
|
weekly(cronIdentifier, schedule, functionReference, ...args) {
|
|
197
199
|
const dayOfWeek = validatedDayOfWeek(schedule.dayOfWeek);
|
|
@@ -224,8 +226,8 @@ export class Crons {
|
|
|
224
226
|
*
|
|
225
227
|
* @param cronIdentifier - A unique name for this scheduled job.
|
|
226
228
|
* @param schedule - What day and time (UTC) each month to run this function.
|
|
227
|
-
* @param functionReference - A {@link FunctionReference}
|
|
228
|
-
* to schedule.
|
|
229
|
+
* @param functionReference - A {@link FunctionReference} or
|
|
230
|
+
* {@link FunctionReference_future} for the function to schedule.
|
|
229
231
|
* @param args - The arguments to the function.
|
|
230
232
|
*/
|
|
231
233
|
monthly(cronIdentifier, schedule, functionReference, ...args) {
|
|
@@ -255,8 +257,8 @@ export class Crons {
|
|
|
255
257
|
*
|
|
256
258
|
* @param cronIdentifier - A unique name for this scheduled job.
|
|
257
259
|
* @param cron - Cron string like `"15 7 * * *"` (Every day at 7:15 UTC)
|
|
258
|
-
* @param functionReference - A {@link FunctionReference}
|
|
259
|
-
* to schedule.
|
|
260
|
+
* @param functionReference - A {@link FunctionReference} or
|
|
261
|
+
* {@link FunctionReference_future} for the function to schedule.
|
|
260
262
|
* @param args - The arguments to the function.
|
|
261
263
|
*/
|
|
262
264
|
cron(cronIdentifier, cron, functionReference, ...args) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/cron.ts"],
|
|
4
|
-
"sourcesContent": ["import { getFunctionName, OptionalRestArgs } from \"../server/api.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport { convexToJson, JSONValue, Value } from \"../values/index.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\nimport { SchedulableFunctionReference } from \"./scheduler.js\";\n\ntype CronSchedule = {\n type: \"cron\";\n cron: string;\n};\n/** @public */\nexport type IntervalSchedule =\n | { type: \"interval\"; seconds: number }\n | { type: \"interval\"; minutes: number }\n | { type: \"interval\"; hours: number };\n/** @public */\nexport type HourlySchedule = {\n type: \"hourly\";\n minuteUTC?: number;\n};\n/** @public */\nexport type DailySchedule = {\n type: \"daily\";\n hourUTC: number;\n minuteUTC?: number;\n};\nconst DAYS_OF_WEEK = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n] as const;\ntype DayOfWeek = (typeof DAYS_OF_WEEK)[number];\n/** @public */\nexport type WeeklySchedule = {\n type: \"weekly\";\n dayOfWeek: DayOfWeek;\n hourUTC: number;\n minuteUTC?: number;\n};\n/** @public */\nexport type MonthlySchedule = {\n type: \"monthly\";\n day: number;\n hourUTC: number;\n minuteUTC?: number;\n};\n\n// Duplicating types so docstrings are visible in signatures:\n// `Expand<Omit<MonthlySchedule, \"type\">>` doesn't preserve docstrings.\n// When we get to TypeScript 4.9, `satisfies` would go nicely here.\n\n/** @public */\nexport type Interval =\n | {\n /**\n * Run a job every `seconds` seconds, beginning\n * when the job is first deployed to Convex.\n */\n seconds: number;\n minutes?: undefined;\n hours?: undefined;\n }\n | {\n /**\n * Run a job every `minutes` minutes, beginning\n * when the job is first deployed to Convex.\n */\n minutes: number;\n seconds?: undefined;\n hours?: undefined;\n }\n | {\n /**\n * Run a job every `hours` hours, beginning when\n * when the job is first deployed to Convex.\n */\n hours: number;\n seconds?: undefined;\n minutes?: undefined;\n };\n\n/** @public */\nexport type Hourly = {\n /**\n * Minutes past the hour, 0-59. If omitted, Convex picks a minute for you\n * and spreads runs across the hour so your job isn't tied to the busy top\n * of the hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Daily = {\n /**\n * 0-23, hour of day. Remember, this is UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember, this is UTC. If omitted, Convex picks a\n * minute for you and spreads runs across the hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Monthly = {\n /**\n * 1-31, day of month. Days greater that 28 will not run every month.\n */\n day: number;\n /**\n * 0-23, hour of day. Remember to convert from your own time zone to UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember to convert from your own time zone to UTC.\n * If omitted, Convex picks a minute for you and spreads runs across the\n * hour.\n */\n minuteUTC?: number;\n};\n/** @public */\nexport type Weekly = {\n /**\n * \"monday\", \"tuesday\", etc.\n */\n dayOfWeek: DayOfWeek;\n /**\n * 0-23, hour of day. Remember to convert from your own time zone to UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember to convert from your own time zone to UTC.\n * If omitted, Convex picks a minute for you and spreads runs across the\n * hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Schedule =\n | CronSchedule\n | IntervalSchedule\n | HourlySchedule\n | DailySchedule\n | WeeklySchedule\n | MonthlySchedule;\n\n/**\n * A schedule to run a Convex mutation or action on.\n * You can schedule Convex functions to run regularly with\n * {@link interval} and exporting it.\n *\n * @public\n **/\nexport interface CronJob {\n name: string;\n args: JSONValue;\n schedule: Schedule;\n}\n\n/**\n * Create a CronJobs object to schedule recurring tasks.\n *\n * ```js\n * // convex/crons.js\n * import { cronJobs } from 'convex/server';\n * import { api } from \"./_generated/api\";\n *\n * const crons = cronJobs();\n * crons.weekly(\n * \"weekly re-engagement email\",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.emails.send\n * )\n * export default crons;\n * ```\n *\n * @public\n */\nexport const cronJobs = () => new Crons();\n\n/**\n * @public\n *\n * This is a cron string. They're complicated!\n */\ntype CronString = string;\n\nfunction validateIntervalNumber(n: number) {\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(\"Interval must be an integer greater than 0\");\n }\n}\n\nfunction validatedDayOfMonth(n: number) {\n if (!Number.isInteger(n) || n < 1 || n > 31) {\n throw new Error(\"Day of month must be an integer from 1 to 31\");\n }\n return n;\n}\n\nfunction validatedDayOfWeek(s: string) {\n if (!DAYS_OF_WEEK.includes(s as DayOfWeek)) {\n throw new Error('Day of week must be a string like \"monday\".');\n }\n return s as DayOfWeek;\n}\n\nfunction validatedHourOfDay(n: number) {\n if (!Number.isInteger(n) || n < 0 || n > 23) {\n throw new Error(\"Hour of day must be an integer from 0 to 23\");\n }\n return n;\n}\n\nfunction validatedMinuteOfHour(n: number) {\n if (!Number.isInteger(n) || n < 0 || n > 59) {\n throw new Error(\"Minute of hour must be an integer from 0 to 59\");\n }\n return n;\n}\n\n// `minuteUTC` is optional: when omitted the backend picks a minute per job and\n// spreads runs across the hour. Only validate when a minute was provided.\nfunction validatedOptionalMinuteOfHour(n: number | undefined) {\n return n === undefined ? undefined : validatedMinuteOfHour(n);\n}\n\n// `crons.hourly()` lets the schedule object be omitted entirely. Tell the two\n// call shapes apart by whether the second argument resolves to a function\n// reference (the way the scheduler syscalls do) rather than a schedule object.\nfunction isSchedulableFunctionReference(\n arg: Hourly | SchedulableFunctionReference,\n): arg is SchedulableFunctionReference {\n try {\n getFunctionAddress(arg);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction validatedCronString(s: string) {\n return s;\n}\n\nfunction validatedCronIdentifier(s: string) {\n if (!s.match(/^[ -~]*$/)) {\n throw new Error(\n `Invalid cron identifier ${s}: use ASCII letters that are not control characters`,\n );\n }\n return s;\n}\n\n/**\n * A class for scheduling cron jobs.\n *\n * To learn more see the documentation at https://docs.convex.dev/scheduling/cron-jobs\n *\n * @public\n */\nexport class Crons {\n crons: Record<string, CronJob>;\n isCrons: true;\n constructor() {\n this.isCrons = true;\n this.crons = {};\n }\n\n /** @internal */\n schedule(\n cronIdentifier: string,\n schedule: Schedule,\n functionReference: SchedulableFunctionReference,\n args?: Record<string, Value>,\n ) {\n const cronArgs = parseArgs(args);\n validatedCronIdentifier(cronIdentifier);\n if (cronIdentifier in this.crons) {\n throw new Error(`Cron identifier registered twice: ${cronIdentifier}`);\n }\n this.crons[cronIdentifier] = {\n name: getFunctionName(functionReference),\n args: [convexToJson(cronArgs)],\n schedule: schedule,\n };\n }\n\n /**\n * Schedule a mutation or action to run at some interval.\n *\n * ```js\n * crons.interval(\"Clear presence data\", {seconds: 30}, api.presence.clear);\n * ```\n *\n * @param identifier - A unique name for this scheduled job.\n * @param schedule - The time between runs for this scheduled job.\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n * @param args - The arguments to the function.\n */\n interval<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n schedule: Interval,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const s = schedule;\n const hasSeconds = +(\"seconds\" in s && s.seconds !== undefined);\n const hasMinutes = +(\"minutes\" in s && s.minutes !== undefined);\n const hasHours = +(\"hours\" in s && s.hours !== undefined);\n const total = hasSeconds + hasMinutes + hasHours;\n if (total !== 1) {\n throw new Error(\"Must specify one of seconds, minutes, or hours\");\n }\n if (hasSeconds) {\n validateIntervalNumber(schedule.seconds!);\n } else if (hasMinutes) {\n validateIntervalNumber(schedule.minutes!);\n } else if (hasHours) {\n validateIntervalNumber(schedule.hours!);\n }\n this.schedule(\n cronIdentifier,\n { ...schedule, type: \"interval\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on an hourly basis.\n *\n * ```js\n * crons.hourly(\n * \"Reset high scores\",\n * {\n * minuteUTC: 30,\n * },\n * api.scores.reset\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What minute (UTC) of each hour to run this function. May\n * be omitted to let Convex pick a minute and spread runs across the hour.\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n * @param args - The arguments to the function.\n */\n hourly<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ): void;\n hourly<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n schedule: Hourly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ): void;\n hourly<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n scheduleOrFunctionReference: Hourly | FuncRef,\n functionReferenceOrArg?: FuncRef | Record<string, Value>,\n ...args: any[]\n ): void {\n // The schedule object may be omitted, so the second argument is either the\n // function reference (no schedule) or the schedule.\n if (isSchedulableFunctionReference(scheduleOrFunctionReference)) {\n this.schedule(\n cronIdentifier,\n { type: \"hourly\" },\n scheduleOrFunctionReference,\n functionReferenceOrArg as Record<string, Value> | undefined,\n );\n return;\n }\n const minuteUTC = validatedOptionalMinuteOfHour(\n scheduleOrFunctionReference.minuteUTC,\n );\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { type: \"hourly\" }\n : { minuteUTC, type: \"hourly\" },\n functionReferenceOrArg as FuncRef,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a daily basis.\n *\n * ```js\n * crons.daily(\n * \"Reset high scores\",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.scores.reset\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What time (UTC) each day to run this function.\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n * @param args - The arguments to the function.\n */\n daily<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n schedule: Daily,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { hourUTC, type: \"daily\" }\n : { hourUTC, minuteUTC, type: \"daily\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a weekly basis.\n *\n * ```js\n * crons.weekly(\n * \"Weekly re-engagement email\",\n * {\n * dayOfWeek: \"Tuesday\",\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.emails.send\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What day and time (UTC) each week to run this function.\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n */\n weekly<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n schedule: Weekly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const dayOfWeek = validatedDayOfWeek(schedule.dayOfWeek);\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { dayOfWeek, hourUTC, type: \"weekly\" }\n : { dayOfWeek, hourUTC, minuteUTC, type: \"weekly\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a monthly basis.\n *\n * Note that some months have fewer days than others, so e.g. a function\n * scheduled to run on the 30th will not run in February.\n *\n * ```js\n * crons.monthly(\n * \"Bill customers at \",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * day: 1,\n * },\n * api.billing.billCustomers\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What day and time (UTC) each month to run this function.\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n * @param args - The arguments to the function.\n */\n monthly<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n schedule: Monthly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const day = validatedDayOfMonth(schedule.day);\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { day, hourUTC, type: \"monthly\" }\n : { day, hourUTC, minuteUTC, type: \"monthly\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a recurring basis.\n *\n * Like the unix command `cron`, Sunday is 0, Monday is 1, etc.\n *\n * ```\n * \u250C\u2500 minute (0 - 59)\n * \u2502 \u250C\u2500 hour (0 - 23)\n * \u2502 \u2502 \u250C\u2500 day of the month (1 - 31)\n * \u2502 \u2502 \u2502 \u250C\u2500 month (1 - 12)\n * \u2502 \u2502 \u2502 \u2502 \u250C\u2500 day of the week (0 - 6) (Sunday to Saturday)\n * \"* * * * *\"\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param cron - Cron string like `\"15 7 * * *\"` (Every day at 7:15 UTC)\n * @param functionReference - A {@link FunctionReference} for the function\n * to schedule.\n * @param args - The arguments to the function.\n */\n cron<FuncRef extends SchedulableFunctionReference>(\n cronIdentifier: string,\n cron: CronString,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const c = validatedCronString(cron);\n this.schedule(\n cronIdentifier,\n { cron: c, type: \"cron\" },\n functionReference,\n ...args,\n );\n }\n\n /** @internal */\n export() {\n return JSON.stringify(this.crons);\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAAA,
|
|
4
|
+
"sourcesContent": ["import {\n FunctionReference_future,\n getFunctionName,\n OptionalRestArgs,\n} from \"../server/api.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport { convexToJson, JSONValue, Value } from \"../values/index.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\nimport { SchedulableFunctionReference } from \"./scheduler.js\";\n\n// Mirrors the constraint on `Scheduler.runAfter` and `Scheduler.runAt`, which\n// is module-local to `scheduler.ts`.\ntype SchedulableFunctionReferenceCompat =\n | SchedulableFunctionReference\n | FunctionReference_future<\"mutation\" | \"action\", \"public\" | \"internal\">;\n\ntype CronSchedule = {\n type: \"cron\";\n cron: string;\n};\n/** @public */\nexport type IntervalSchedule =\n | { type: \"interval\"; seconds: number }\n | { type: \"interval\"; minutes: number }\n | { type: \"interval\"; hours: number };\n/** @public */\nexport type HourlySchedule = {\n type: \"hourly\";\n minuteUTC?: number;\n};\n/** @public */\nexport type DailySchedule = {\n type: \"daily\";\n hourUTC: number;\n minuteUTC?: number;\n};\nconst DAYS_OF_WEEK = [\n \"sunday\",\n \"monday\",\n \"tuesday\",\n \"wednesday\",\n \"thursday\",\n \"friday\",\n \"saturday\",\n] as const;\ntype DayOfWeek = (typeof DAYS_OF_WEEK)[number];\n/** @public */\nexport type WeeklySchedule = {\n type: \"weekly\";\n dayOfWeek: DayOfWeek;\n hourUTC: number;\n minuteUTC?: number;\n};\n/** @public */\nexport type MonthlySchedule = {\n type: \"monthly\";\n day: number;\n hourUTC: number;\n minuteUTC?: number;\n};\n\n// Duplicating types so docstrings are visible in signatures:\n// `Expand<Omit<MonthlySchedule, \"type\">>` doesn't preserve docstrings.\n// When we get to TypeScript 4.9, `satisfies` would go nicely here.\n\n/** @public */\nexport type Interval =\n | {\n /**\n * Run a job every `seconds` seconds, beginning\n * when the job is first deployed to Convex.\n */\n seconds: number;\n minutes?: undefined;\n hours?: undefined;\n }\n | {\n /**\n * Run a job every `minutes` minutes, beginning\n * when the job is first deployed to Convex.\n */\n minutes: number;\n seconds?: undefined;\n hours?: undefined;\n }\n | {\n /**\n * Run a job every `hours` hours, beginning when\n * when the job is first deployed to Convex.\n */\n hours: number;\n seconds?: undefined;\n minutes?: undefined;\n };\n\n/** @public */\nexport type Hourly = {\n /**\n * Minutes past the hour, 0-59. If omitted, Convex picks a minute for you\n * and spreads runs across the hour so your job isn't tied to the busy top\n * of the hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Daily = {\n /**\n * 0-23, hour of day. Remember, this is UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember, this is UTC. If omitted, Convex picks a\n * minute for you and spreads runs across the hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Monthly = {\n /**\n * 1-31, day of month. Days greater that 28 will not run every month.\n */\n day: number;\n /**\n * 0-23, hour of day. Remember to convert from your own time zone to UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember to convert from your own time zone to UTC.\n * If omitted, Convex picks a minute for you and spreads runs across the\n * hour.\n */\n minuteUTC?: number;\n};\n/** @public */\nexport type Weekly = {\n /**\n * \"monday\", \"tuesday\", etc.\n */\n dayOfWeek: DayOfWeek;\n /**\n * 0-23, hour of day. Remember to convert from your own time zone to UTC.\n */\n hourUTC: number;\n /**\n * 0-59, minute of hour. Remember to convert from your own time zone to UTC.\n * If omitted, Convex picks a minute for you and spreads runs across the\n * hour.\n */\n minuteUTC?: number;\n};\n\n/** @public */\nexport type Schedule =\n | CronSchedule\n | IntervalSchedule\n | HourlySchedule\n | DailySchedule\n | WeeklySchedule\n | MonthlySchedule;\n\n/**\n * A schedule to run a Convex mutation or action on.\n * You can schedule Convex functions to run regularly with\n * {@link interval} and exporting it.\n *\n * @public\n **/\nexport interface CronJob {\n name: string;\n args: JSONValue;\n schedule: Schedule;\n}\n\n/**\n * Create a CronJobs object to schedule recurring tasks.\n *\n * ```js\n * // convex/crons.js\n * import { cronJobs } from 'convex/server';\n * import { api } from \"./_generated/api\";\n *\n * const crons = cronJobs();\n * crons.weekly(\n * \"weekly re-engagement email\",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.emails.send\n * )\n * export default crons;\n * ```\n *\n * @public\n */\nexport const cronJobs = () => new Crons();\n\n/**\n * @public\n *\n * This is a cron string. They're complicated!\n */\ntype CronString = string;\n\nfunction validateIntervalNumber(n: number) {\n if (!Number.isInteger(n) || n <= 0) {\n throw new Error(\"Interval must be an integer greater than 0\");\n }\n}\n\nfunction validatedDayOfMonth(n: number) {\n if (!Number.isInteger(n) || n < 1 || n > 31) {\n throw new Error(\"Day of month must be an integer from 1 to 31\");\n }\n return n;\n}\n\nfunction validatedDayOfWeek(s: string) {\n if (!DAYS_OF_WEEK.includes(s as DayOfWeek)) {\n throw new Error('Day of week must be a string like \"monday\".');\n }\n return s as DayOfWeek;\n}\n\nfunction validatedHourOfDay(n: number) {\n if (!Number.isInteger(n) || n < 0 || n > 23) {\n throw new Error(\"Hour of day must be an integer from 0 to 23\");\n }\n return n;\n}\n\nfunction validatedMinuteOfHour(n: number) {\n if (!Number.isInteger(n) || n < 0 || n > 59) {\n throw new Error(\"Minute of hour must be an integer from 0 to 59\");\n }\n return n;\n}\n\n// `minuteUTC` is optional: when omitted the backend picks a minute per job and\n// spreads runs across the hour. Only validate when a minute was provided.\nfunction validatedOptionalMinuteOfHour(n: number | undefined) {\n return n === undefined ? undefined : validatedMinuteOfHour(n);\n}\n\n// `crons.hourly()` lets the schedule object be omitted entirely. Tell the two\n// call shapes apart by whether the second argument resolves to a function\n// reference (the way the scheduler syscalls do) rather than a schedule object.\nfunction isSchedulableFunctionReference(\n arg: Hourly | SchedulableFunctionReferenceCompat,\n): arg is SchedulableFunctionReferenceCompat {\n try {\n getFunctionAddress(arg);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction validatedCronString(s: string) {\n return s;\n}\n\nfunction validatedCronIdentifier(s: string) {\n if (!s.match(/^[ -~]*$/)) {\n throw new Error(\n `Invalid cron identifier ${s}: use ASCII letters that are not control characters`,\n );\n }\n return s;\n}\n\n/**\n * A class for scheduling cron jobs.\n *\n * To learn more see the documentation at https://docs.convex.dev/scheduling/cron-jobs\n *\n * @public\n */\nexport class Crons {\n crons: Record<string, CronJob>;\n isCrons: true;\n constructor() {\n this.isCrons = true;\n this.crons = {};\n }\n\n /** @internal */\n schedule(\n cronIdentifier: string,\n schedule: Schedule,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n ) {\n const cronArgs = parseArgs(args);\n validatedCronIdentifier(cronIdentifier);\n if (cronIdentifier in this.crons) {\n throw new Error(`Cron identifier registered twice: ${cronIdentifier}`);\n }\n this.crons[cronIdentifier] = {\n name: getFunctionName(functionReference),\n args: [convexToJson(cronArgs)],\n schedule: schedule,\n };\n }\n\n /**\n * Schedule a mutation or action to run at some interval.\n *\n * ```js\n * crons.interval(\"Clear presence data\", {seconds: 30}, api.presence.clear);\n * ```\n *\n * @param identifier - A unique name for this scheduled job.\n * @param schedule - The time between runs for this scheduled job.\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n * @param args - The arguments to the function.\n */\n interval<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n schedule: Interval,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const s = schedule;\n const hasSeconds = +(\"seconds\" in s && s.seconds !== undefined);\n const hasMinutes = +(\"minutes\" in s && s.minutes !== undefined);\n const hasHours = +(\"hours\" in s && s.hours !== undefined);\n const total = hasSeconds + hasMinutes + hasHours;\n if (total !== 1) {\n throw new Error(\"Must specify one of seconds, minutes, or hours\");\n }\n if (hasSeconds) {\n validateIntervalNumber(schedule.seconds!);\n } else if (hasMinutes) {\n validateIntervalNumber(schedule.minutes!);\n } else if (hasHours) {\n validateIntervalNumber(schedule.hours!);\n }\n this.schedule(\n cronIdentifier,\n { ...schedule, type: \"interval\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on an hourly basis.\n *\n * ```js\n * crons.hourly(\n * \"Reset high scores\",\n * {\n * minuteUTC: 30,\n * },\n * api.scores.reset\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What minute (UTC) of each hour to run this function. May\n * be omitted to let Convex pick a minute and spread runs across the hour.\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n * @param args - The arguments to the function.\n */\n hourly<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ): void;\n hourly<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n schedule: Hourly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ): void;\n hourly<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n scheduleOrFunctionReference: Hourly | FuncRef,\n functionReferenceOrArg?: FuncRef | Record<string, Value>,\n ...args: any[]\n ): void {\n // The schedule object may be omitted, so the second argument is either the\n // function reference (no schedule) or the schedule.\n if (isSchedulableFunctionReference(scheduleOrFunctionReference)) {\n this.schedule(\n cronIdentifier,\n { type: \"hourly\" },\n scheduleOrFunctionReference,\n functionReferenceOrArg as Record<string, Value> | undefined,\n );\n return;\n }\n const minuteUTC = validatedOptionalMinuteOfHour(\n scheduleOrFunctionReference.minuteUTC,\n );\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { type: \"hourly\" }\n : { minuteUTC, type: \"hourly\" },\n functionReferenceOrArg as FuncRef,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a daily basis.\n *\n * ```js\n * crons.daily(\n * \"Reset high scores\",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.scores.reset\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What time (UTC) each day to run this function.\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n * @param args - The arguments to the function.\n */\n daily<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n schedule: Daily,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { hourUTC, type: \"daily\" }\n : { hourUTC, minuteUTC, type: \"daily\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a weekly basis.\n *\n * ```js\n * crons.weekly(\n * \"Weekly re-engagement email\",\n * {\n * dayOfWeek: \"Tuesday\",\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * },\n * api.emails.send\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What day and time (UTC) each week to run this function.\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n */\n weekly<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n schedule: Weekly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const dayOfWeek = validatedDayOfWeek(schedule.dayOfWeek);\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { dayOfWeek, hourUTC, type: \"weekly\" }\n : { dayOfWeek, hourUTC, minuteUTC, type: \"weekly\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a monthly basis.\n *\n * Note that some months have fewer days than others, so e.g. a function\n * scheduled to run on the 30th will not run in February.\n *\n * ```js\n * crons.monthly(\n * \"Bill customers at \",\n * {\n * hourUTC: 17, // (9:30am Pacific/10:30am Daylight Savings Pacific)\n * minuteUTC: 30,\n * day: 1,\n * },\n * api.billing.billCustomers\n * )\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param schedule - What day and time (UTC) each month to run this function.\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n * @param args - The arguments to the function.\n */\n monthly<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n schedule: Monthly,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const day = validatedDayOfMonth(schedule.day);\n const hourUTC = validatedHourOfDay(schedule.hourUTC);\n const minuteUTC = validatedOptionalMinuteOfHour(schedule.minuteUTC);\n this.schedule(\n cronIdentifier,\n minuteUTC === undefined\n ? { day, hourUTC, type: \"monthly\" }\n : { day, hourUTC, minuteUTC, type: \"monthly\" },\n functionReference,\n ...args,\n );\n }\n\n /**\n * Schedule a mutation or action to run on a recurring basis.\n *\n * Like the unix command `cron`, Sunday is 0, Monday is 1, etc.\n *\n * ```\n * \u250C\u2500 minute (0 - 59)\n * \u2502 \u250C\u2500 hour (0 - 23)\n * \u2502 \u2502 \u250C\u2500 day of the month (1 - 31)\n * \u2502 \u2502 \u2502 \u250C\u2500 month (1 - 12)\n * \u2502 \u2502 \u2502 \u2502 \u250C\u2500 day of the week (0 - 6) (Sunday to Saturday)\n * \"* * * * *\"\n * ```\n *\n * @param cronIdentifier - A unique name for this scheduled job.\n * @param cron - Cron string like `\"15 7 * * *\"` (Every day at 7:15 UTC)\n * @param functionReference - A {@link FunctionReference} or\n * {@link FunctionReference_future} for the function to schedule.\n * @param args - The arguments to the function.\n */\n cron<FuncRef extends SchedulableFunctionReferenceCompat>(\n cronIdentifier: string,\n cron: CronString,\n functionReference: FuncRef,\n ...args: OptionalRestArgs<FuncRef>\n ) {\n const c = validatedCronString(cron);\n this.schedule(\n cronIdentifier,\n { cron: c, type: \"cron\" },\n functionReference,\n ...args,\n );\n }\n\n /** @internal */\n export() {\n return JSON.stringify(this.crons);\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAAA;AAAA,EAEE;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,oBAAsC;AAC/C,SAAS,0BAA0B;AA6BnC,MAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAyJO,aAAM,WAAW,MAAM,IAAI,MAAM;AASxC,SAAS,uBAAuB,GAAW;AACzC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,KAAK,GAAG;AAClC,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACF;AAEA,SAAS,oBAAoB,GAAW;AACtC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,IAAI;AAC3C,UAAM,IAAI,MAAM,8CAA8C;AAAA,EAChE;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,GAAW;AACrC,MAAI,CAAC,aAAa,SAAS,CAAc,GAAG;AAC1C,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;AAEA,SAAS,mBAAmB,GAAW;AACrC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,IAAI;AAC3C,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;AAEA,SAAS,sBAAsB,GAAW;AACxC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,IA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
"sources": ["../../../../src/server/impl/actions_impl.ts"],
|
|
4
|
-
"sourcesContent": ["import { convexToJson, jsonToConvex, Value } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport {
|
|
5
|
-
"mappings": ";AAAA,SAAS,cAAc,oBAA2B;AAClD,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;
|
|
4
|
+
"sourcesContent": ["import { convexToJson, jsonToConvex, Value } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport {\n FunctionReference,\n FunctionReference_future,\n} from \"../../server/api.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nimport { validateArg } from \"./validate.js\";\n\nfunction syscallArgs(\n requestId: string,\n functionReference: any,\n args?: Record<string, Value>,\n) {\n const address = getFunctionAddress(functionReference);\n return {\n ...address,\n args: convexToJson(parseArgs(args)),\n version,\n requestId,\n };\n}\n\nexport function setupActionCalls(requestId: string) {\n return {\n runQuery: async (\n query:\n | FunctionReference<\"query\", \"public\" | \"internal\">\n | FunctionReference_future<\"query\", \"public\" | \"internal\">,\n args?: Record<string, Value>,\n ): Promise<any> => {\n const result = await performAsyncSyscall(\n \"1.0/actions/query\",\n syscallArgs(requestId, query, args),\n );\n return jsonToConvex(result);\n },\n runMutation: async (\n mutation:\n | FunctionReference<\"mutation\", \"public\" | \"internal\">\n | FunctionReference_future<\"mutation\", \"public\" | \"internal\">,\n args?: Record<string, Value>,\n ): Promise<any> => {\n const result = await performAsyncSyscall(\n \"1.0/actions/mutation\",\n syscallArgs(requestId, mutation, args),\n );\n return jsonToConvex(result);\n },\n runAction: async (\n action:\n | FunctionReference<\"action\", \"public\" | \"internal\">\n | FunctionReference_future<\"action\", \"public\" | \"internal\">,\n args?: Record<string, Value>,\n ): Promise<any> => {\n const result = await performAsyncSyscall(\n \"1.0/actions/action\",\n syscallArgs(requestId, action, args),\n );\n return jsonToConvex(result);\n },\n };\n}\n\n/**\n * Get a short-lived credential for calling a Convex-managed service.\n *\n * This function can only be called while an action is running. The credential\n * is scoped to the current deployment and should be sent as a bearer token.\n * Repeated calls in the same action reuse one token; a failed mint is not\n * cached, so a later call retries.\n *\n * @param service - The service the credential may access.\n * @returns A JWT to send as `Authorization: Bearer <token>`. Keep it inside\n * the action: don't return it to clients or store it in environment\n * variables.\n */\nexport async function getServiceToken(service: \"ai-gateway\"): Promise<string> {\n validateArg(service, 1, \"getServiceToken\", \"service\");\n if (service !== \"ai-gateway\") {\n throw new Error(`Unsupported service \"${String(service)}\"`);\n }\n return await performAsyncSyscall(\"1.0/createServiceToken\", {\n service,\n version,\n });\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,cAAc,oBAA2B;AAClD,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAK1B,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAE5B,SAAS,YACP,WACA,mBACA,MACA;AACA,QAAM,UAAU,mBAAmB,iBAAiB;AACpD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,aAAa,UAAU,IAAI,CAAC;AAAA,IAClC;AAAA,IACA;AAAA,EACF;AACF;AAEO,gBAAS,iBAAiB,WAAmB;AAClD,SAAO;AAAA,IACL,UAAU,OACR,OAGA,SACiB;AACjB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA,YAAY,WAAW,OAAO,IAAI;AAAA,MACpC;AACA,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,IACA,aAAa,OACX,UAGA,SACiB;AACjB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA,YAAY,WAAW,UAAU,IAAI;AAAA,MACvC;AACA,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,IACA,WAAW,OACT,QAGA,SACiB;AACjB,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA,YAAY,WAAW,QAAQ,IAAI;AAAA,MACrC;AACA,aAAO,aAAa,MAAM;AAAA,IAC5B;AAAA,EACF;AACF;AAeA,sBAAsB,gBAAgB,SAAwC;AAC5E,cAAY,SAAS,GAAG,mBAAmB,SAAS;AACpD,MAAI,YAAY,cAAc;AAC5B,UAAM,IAAI,MAAM,wBAAwB,OAAO,OAAO,CAAC,GAAG;AAAA,EAC5D;AACA,SAAO,MAAM,oBAAoB,0BAA0B;AAAA,IACzD;AAAA,IACA;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
import { jsonToConvex } from "../../values/index.js";
|
|
3
|
-
import { performAsyncSyscall } from "./syscall.js";
|
|
3
|
+
import { performAsyncSyscall, performSyscall } from "./syscall.js";
|
|
4
4
|
async function getTransactionMetrics() {
|
|
5
5
|
let syscallJSON;
|
|
6
6
|
try {
|
|
@@ -37,6 +37,10 @@ async function getDeploymentMetadata() {
|
|
|
37
37
|
class: result.class
|
|
38
38
|
};
|
|
39
39
|
}
|
|
40
|
+
function getSnapshotTs() {
|
|
41
|
+
const syscallJSON = performSyscall("1.0/getSnapshotTs", {});
|
|
42
|
+
return jsonToConvex(syscallJSON);
|
|
43
|
+
}
|
|
40
44
|
async function getRequestMetadata() {
|
|
41
45
|
const { ip, userAgent, requestId, scheduledFunctionId, authToken } = await performAsyncSyscall("1.0/getRequestMetadata", {});
|
|
42
46
|
return { ip, userAgent, requestId, scheduledFunctionId, authToken };
|
|
@@ -49,7 +53,8 @@ export function setupQueryMeta(visibility) {
|
|
|
49
53
|
visibility
|
|
50
54
|
}),
|
|
51
55
|
getTransactionMetrics,
|
|
52
|
-
getDeploymentMetadata
|
|
56
|
+
getDeploymentMetadata,
|
|
57
|
+
getSnapshotTs
|
|
53
58
|
};
|
|
54
59
|
}
|
|
55
60
|
export function setupMutationMeta(visibility) {
|
|
@@ -61,7 +66,8 @@ export function setupMutationMeta(visibility) {
|
|
|
61
66
|
}),
|
|
62
67
|
getTransactionMetrics,
|
|
63
68
|
getDeploymentMetadata,
|
|
64
|
-
getRequestMetadata
|
|
69
|
+
getRequestMetadata,
|
|
70
|
+
getSnapshotTs
|
|
65
71
|
};
|
|
66
72
|
}
|
|
67
73
|
export function setupActionMeta(visibility) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/server/impl/meta_impl.ts"],
|
|
4
|
-
"sourcesContent": ["import { jsonToConvex } from \"../../values/index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n RequestMetadata,\n FunctionMetadata,\n TransactionMetrics,\n DeploymentMetadata,\n} from \"../meta.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\n\nasync function getTransactionMetrics(): Promise<TransactionMetrics> {\n let syscallJSON;\n try {\n syscallJSON = await performAsyncSyscall(\"1.0/getTransactionMetrics\", {});\n } catch (e: any) {\n if (e.message?.includes(\"Unknown async operation\")) {\n throw new Error(\n \"getTransactionMetrics() can only be called from a query or mutation. \" +\n \"It is not available in actions or outside of a Convex function.\",\n );\n }\n throw e;\n }\n return jsonToConvex(syscallJSON) as any;\n}\n\nasync function getFunctionMetadata(): Promise<{\n name: string;\n componentPath: string;\n}> {\n const { name, componentPath } = await performAsyncSyscall(\n \"1.0/getFunctionMetadata\",\n {},\n );\n return {\n name,\n componentPath,\n };\n}\n\nasync function getDeploymentMetadata(): Promise<DeploymentMetadata> {\n const syscallJSON = await performAsyncSyscall(\n \"1.0/getDeploymentMetadata\",\n {},\n );\n const result = jsonToConvex(syscallJSON) as any;\n return {\n name: result.name,\n region: result.region ?? null,\n class: result.class,\n };\n}\n\nasync function getRequestMetadata(): Promise<RequestMetadata> {\n const { ip, userAgent, requestId, scheduledFunctionId, authToken } =\n await performAsyncSyscall(\"1.0/getRequestMetadata\", {});\n return { ip, userAgent, requestId, scheduledFunctionId, authToken };\n}\n\nexport function setupQueryMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): QueryMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"query\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n };\n}\n\nexport function setupMutationMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): MutationMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"mutation\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n\nexport function setupActionMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): ActionMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"action\",\n visibility,\n }),\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,oBAAoB;AAU7B,SAAS,
|
|
4
|
+
"sourcesContent": ["import { jsonToConvex } from \"../../values/index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n RequestMetadata,\n FunctionMetadata,\n TransactionMetrics,\n DeploymentMetadata,\n} from \"../meta.js\";\nimport { performAsyncSyscall, performSyscall } from \"./syscall.js\";\n\nasync function getTransactionMetrics(): Promise<TransactionMetrics> {\n let syscallJSON;\n try {\n syscallJSON = await performAsyncSyscall(\"1.0/getTransactionMetrics\", {});\n } catch (e: any) {\n if (e.message?.includes(\"Unknown async operation\")) {\n throw new Error(\n \"getTransactionMetrics() can only be called from a query or mutation. \" +\n \"It is not available in actions or outside of a Convex function.\",\n );\n }\n throw e;\n }\n return jsonToConvex(syscallJSON) as any;\n}\n\nasync function getFunctionMetadata(): Promise<{\n name: string;\n componentPath: string;\n}> {\n const { name, componentPath } = await performAsyncSyscall(\n \"1.0/getFunctionMetadata\",\n {},\n );\n return {\n name,\n componentPath,\n };\n}\n\nasync function getDeploymentMetadata(): Promise<DeploymentMetadata> {\n const syscallJSON = await performAsyncSyscall(\n \"1.0/getDeploymentMetadata\",\n {},\n );\n const result = jsonToConvex(syscallJSON) as any;\n return {\n name: result.name,\n region: result.region ?? null,\n class: result.class,\n };\n}\n\nfunction getSnapshotTs(): bigint {\n const syscallJSON = performSyscall(\"1.0/getSnapshotTs\", {});\n return jsonToConvex(syscallJSON) as bigint;\n}\n\nasync function getRequestMetadata(): Promise<RequestMetadata> {\n const { ip, userAgent, requestId, scheduledFunctionId, authToken } =\n await performAsyncSyscall(\"1.0/getRequestMetadata\", {});\n return { ip, userAgent, requestId, scheduledFunctionId, authToken };\n}\n\nexport function setupQueryMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): QueryMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"query\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n getSnapshotTs,\n };\n}\n\nexport function setupMutationMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): MutationMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"mutation\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n getRequestMetadata,\n getSnapshotTs,\n };\n}\n\nexport function setupActionMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): ActionMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"action\",\n visibility,\n }),\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,oBAAoB;AAU7B,SAAS,qBAAqB,sBAAsB;AAEpD,eAAe,wBAAqD;AAClE,MAAI;AACJ,MAAI;AACF,kBAAc,MAAM,oBAAoB,6BAA6B,CAAC,CAAC;AAAA,EACzE,SAAS,GAAQ;AACf,QAAI,EAAE,SAAS,SAAS,yBAAyB,GAAG;AAClD,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACA,SAAO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
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/server/impl/scheduler_impl.ts"],
|
|
4
|
-
"sourcesContent": ["import { convexToJson, Value } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { SchedulableFunctionReference, Scheduler } from \"../scheduler.js\";\nimport { Id } from \"../../values/value.js\";\nimport { validateArg } from \"./validate.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\n\nexport function setupMutationScheduler(): Scheduler {\n return {\n runAfter: async (\n delayMs: number,\n functionReference:
|
|
5
|
-
"mappings": ";AAAA,SAAS,oBAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;
|
|
4
|
+
"sourcesContent": ["import { convexToJson, Value } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { SchedulableFunctionReference, Scheduler } from \"../scheduler.js\";\nimport { FunctionReference_future } from \"../api.js\";\nimport { Id } from \"../../values/value.js\";\nimport { validateArg } from \"./validate.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\n\n// Mirrors the constraint on `Scheduler.runAfter` and `Scheduler.runAt`, which\n// is module-local to `scheduler.ts`.\ntype SchedulableFunctionReferenceCompat =\n | SchedulableFunctionReference\n | FunctionReference_future<\"mutation\" | \"action\", \"public\" | \"internal\">;\n\nexport function setupMutationScheduler(): Scheduler {\n return {\n runAfter: async (\n delayMs: number,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n ) => {\n const syscallArgs = runAfterSyscallArgs(delayMs, functionReference, args);\n return await performAsyncSyscall(\"1.0/schedule\", syscallArgs);\n },\n runAt: async (\n ms_since_epoch_or_date: number | Date,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n ) => {\n const syscallArgs = runAtSyscallArgs(\n ms_since_epoch_or_date,\n functionReference,\n args,\n );\n return await performAsyncSyscall(\"1.0/schedule\", syscallArgs);\n },\n cancel: async (id: Id<\"_scheduled_functions\">) => {\n validateArg(id, 1, \"cancel\", \"id\");\n const args = { id: convexToJson(id) };\n await performAsyncSyscall(\"1.0/cancel_job\", args);\n },\n };\n}\n\nexport function setupActionScheduler(requestId: string): Scheduler {\n return {\n runAfter: async (\n delayMs: number,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n ) => {\n const syscallArgs = {\n requestId,\n ...runAfterSyscallArgs(delayMs, functionReference, args),\n };\n return await performAsyncSyscall(\"1.0/actions/schedule\", syscallArgs);\n },\n runAt: async (\n ms_since_epoch_or_date: number | Date,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n ) => {\n const syscallArgs = {\n requestId,\n ...runAtSyscallArgs(ms_since_epoch_or_date, functionReference, args),\n };\n return await performAsyncSyscall(\"1.0/actions/schedule\", syscallArgs);\n },\n cancel: async (id: Id<\"_scheduled_functions\">) => {\n validateArg(id, 1, \"cancel\", \"id\");\n const syscallArgs = {\n requestId,\n id: convexToJson(id),\n };\n return await performAsyncSyscall(\"1.0/actions/cancel_job\", syscallArgs);\n },\n };\n}\n\nfunction runAfterSyscallArgs(\n delayMs: number,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n) {\n if (typeof delayMs !== \"number\") {\n throw new Error(\"`delayMs` must be a number\");\n }\n if (!isFinite(delayMs)) {\n throw new Error(\"`delayMs` must be a finite number\");\n }\n if (delayMs < 0) {\n throw new Error(\"`delayMs` must be non-negative\");\n }\n const functionArgs = parseArgs(args);\n const address = getFunctionAddress(functionReference);\n // Note the syscall expects a unix timestamp, measured in seconds.\n const ts = (Date.now() + delayMs) / 1000.0;\n return {\n ...address,\n ts,\n args: convexToJson(functionArgs),\n version,\n };\n}\n\nfunction runAtSyscallArgs(\n ms_since_epoch_or_date: number | Date,\n functionReference: SchedulableFunctionReferenceCompat,\n args?: Record<string, Value>,\n) {\n let ts;\n if (ms_since_epoch_or_date instanceof Date) {\n ts = ms_since_epoch_or_date.valueOf() / 1000.0;\n } else if (typeof ms_since_epoch_or_date === \"number\") {\n // The timestamp the developer passes is in milliseconds, while the syscall\n // accepts seconds since the epoch.\n ts = ms_since_epoch_or_date / 1000;\n } else {\n throw new Error(\"The invoke time must a Date or a timestamp\");\n }\n const address = getFunctionAddress(functionReference);\n const functionArgs = parseArgs(args);\n return {\n ...address,\n ts,\n args: convexToJson(functionArgs),\n version,\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,oBAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAI1B,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAQ5B,gBAAS,yBAAoC;AAClD,SAAO;AAAA,IACL,UAAU,OACR,SACA,mBACA,SACG;AACH,YAAM,cAAc,oBAAoB,SAAS,mBAAmB,IAAI;AACxE,aAAO,MAAM,oBAAoB,gBAAgB,WAAW;AAAA,IAC9D;AAAA,IACA,OAAO,OACL,wBACA,mBACA,SACG;AACH,YAAM,cAAc;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,aAAO,MAAM,oBAAoB,gBAAgB,WAAW;AAAA,IAC9D;AAAA,IACA,QAAQ,OAAO,OAAmC;AAChD,kBAAY,IAAI,GAAG,UAAU,IAAI;AACjC,YAAM,OAAO,EAAE,IAAI,aAAa,EAAE,EAAE;AACpC,YAAM,oBAAoB,kBAAkB,IAAI;AAAA,IAClD;AAAA,EACF;AACF;AAEO,gBAAS,qBAAqB,WAA8B;AACjE,SAAO;AAAA,IACL,UAAU,OACR,SACA,mBACA,SACG;AACH,YAAM,cAAc;AAAA,QAClB;AAAA,QACA,GAAG,oBAAoB,SAAS,mBAAmB,IAAI;AAAA,MACzD;AACA,aAAO,MAAM,oBAA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