convex 1.46.0 → 1.47.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 +58 -1
- package/dist/browser.bundle.js +7 -1
- package/dist/browser.bundle.js.map +2 -2
- package/dist/cjs/bundler/index.js +5 -4
- package/dist/cjs/bundler/index.js.map +2 -2
- package/dist/cjs/cli/codegen.js +0 -4
- package/dist/cjs/cli/codegen.js.map +2 -2
- package/dist/cjs/cli/configure.js +13 -4
- package/dist/cjs/cli/configure.js.map +2 -2
- package/dist/cjs/cli/deploy.js +27 -2
- package/dist/cjs/cli/deploy.js.map +2 -2
- package/dist/cjs/cli/deploymentSelect.js +2 -2
- package/dist/cjs/cli/deploymentSelect.js.map +2 -2
- package/dist/cjs/cli/dev.js +6 -0
- package/dist/cjs/cli/dev.js.map +2 -2
- package/dist/cjs/cli/env.js +10 -5
- package/dist/cjs/cli/env.js.map +2 -2
- package/dist/cjs/cli/envDefault.js +7 -2
- package/dist/cjs/cli/envDefault.js.map +2 -2
- package/dist/cjs/cli/generatedApi.js.map +1 -1
- package/dist/cjs/cli/lib/api.js +2 -0
- package/dist/cjs/cli/lib/api.js.map +2 -2
- package/dist/cjs/cli/lib/checkForLargeIndexBackfill.js +113 -0
- package/dist/cjs/cli/lib/checkForLargeIndexBackfill.js.map +7 -0
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js +36 -47
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js +58 -39
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js.map +2 -2
- package/dist/cjs/cli/lib/checkForStagedValidatorDeletion.js +90 -0
- package/dist/cjs/cli/lib/checkForStagedValidatorDeletion.js.map +7 -0
- package/dist/cjs/cli/lib/codegen.js.map +2 -2
- package/dist/cjs/cli/lib/command.js +2 -1
- package/dist/cjs/cli/lib/command.js.map +2 -2
- package/dist/cjs/cli/lib/components/definition/bundle.js +37 -11
- package/dist/cjs/cli/lib/components/definition/bundle.js.map +2 -2
- package/dist/cjs/cli/lib/components.js +48 -5
- package/dist/cjs/cli/lib/components.js.map +2 -2
- package/dist/cjs/cli/lib/config.js +56 -17
- package/dist/cjs/cli/lib/config.js.map +2 -2
- package/dist/cjs/cli/lib/deploy2.js +3 -1
- package/dist/cjs/cli/lib/deploy2.js.map +2 -2
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js +30 -2
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js.map +2 -2
- package/dist/cjs/cli/lib/dev.js +5 -0
- package/dist/cjs/cli/lib/dev.js.map +2 -2
- package/dist/cjs/cli/lib/formatValidationProgress.js +47 -0
- package/dist/cjs/cli/lib/formatValidationProgress.js.map +7 -0
- package/dist/cjs/cli/lib/indexes.js.map +1 -1
- package/dist/cjs/cli/lib/mcp/tools/env.js +10 -3
- package/dist/cjs/cli/lib/mcp/tools/env.js.map +2 -2
- package/dist/cjs/cli/lib/run.js +4 -0
- package/dist/cjs/cli/lib/run.js.map +2 -2
- package/dist/cjs/cli/lib/schemaEvaluation.js +62 -0
- package/dist/cjs/cli/lib/schemaEvaluation.js.map +7 -0
- package/dist/cjs/cli/lib/usageLimits.js +4 -2
- package/dist/cjs/cli/lib/usageLimits.js.map +2 -2
- package/dist/cjs/cli/lib/utils/mutex.js +9 -24
- package/dist/cjs/cli/lib/utils/mutex.js.map +2 -2
- package/dist/cjs/cli/lib/utils/utils.js +48 -18
- package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
- package/dist/cjs/cli/projectCreate.js +1 -1
- package/dist/cjs/cli/projectCreate.js.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/server/impl/actions_impl.js +8 -3
- package/dist/cjs/server/impl/actions_impl.js.map +2 -2
- package/dist/cjs/server/impl/storage_impl.js +29 -0
- package/dist/cjs/server/impl/storage_impl.js.map +2 -2
- package/dist/cjs/server/index.js +1 -0
- 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/schema.js +34 -12
- package/dist/cjs/server/schema.js.map +2 -2
- package/dist/cjs/server/storage.js.map +1 -1
- package/dist/cjs/values/validators.js +1 -1
- package/dist/cjs/values/validators.js.map +2 -2
- package/dist/cjs/values/value.js +6 -0
- package/dist/cjs/values/value.js.map +2 -2
- package/dist/cjs-types/bundler/index.d.ts +9 -2
- package/dist/cjs-types/bundler/index.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/configure.d.ts +6 -0
- package/dist/cjs-types/cli/configure.d.ts.map +1 -1
- package/dist/cjs-types/cli/deploy.d.ts +2 -0
- package/dist/cjs-types/cli/deploy.d.ts.map +1 -1
- package/dist/cjs-types/cli/deploymentCreate.d.ts +6 -6
- package/dist/cjs-types/cli/deploymentSelect.d.ts.map +1 -1
- package/dist/cjs-types/cli/dev.d.ts +1 -0
- package/dist/cjs-types/cli/dev.d.ts.map +1 -1
- package/dist/cjs-types/cli/env.d.ts.map +1 -1
- package/dist/cjs-types/cli/envDefault.d.ts.map +1 -1
- package/dist/cjs-types/cli/generatedApi.d.ts +1 -1
- package/dist/cjs-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/api.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForLargeIndexBackfill.d.ts +30 -0
- package/dist/cjs-types/cli/lib/checkForLargeIndexBackfill.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts +5 -7
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts +4 -10
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForStagedValidatorDeletion.d.ts +17 -0
- package/dist/cjs-types/cli/lib/checkForStagedValidatorDeletion.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/codegen.d.ts +0 -3
- package/dist/cjs-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/command.d.ts +2 -0
- package/dist/cjs-types/cli/lib/command.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/components/definition/bundle.d.ts +13 -0
- package/dist/cjs-types/cli/lib/components/definition/bundle.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/components.d.ts +4 -0
- package/dist/cjs-types/cli/lib/components.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/config.d.ts +2 -1
- package/dist/cjs-types/cli/lib/config.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deploy2.d.ts +2 -0
- package/dist/cjs-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts +460 -16
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/dev.d.ts +1 -0
- package/dist/cjs-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/formatValidationProgress.d.ts +8 -0
- package/dist/cjs-types/cli/lib/formatValidationProgress.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/mcp/tools/env.d.ts +8 -5
- package/dist/cjs-types/cli/lib/mcp/tools/env.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/run.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/schemaEvaluation.d.ts +33 -0
- package/dist/cjs-types/cli/lib/schemaEvaluation.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/usageLimits.d.ts +1 -1
- package/dist/cjs-types/cli/lib/usageLimits.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/utils/mutex.d.ts +1 -3
- package/dist/cjs-types/cli/lib/utils/mutex.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/utils/utils.d.ts +10 -2
- 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/server/impl/actions_impl.d.ts +18 -3
- package/dist/cjs-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/storage_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 +63 -0
- package/dist/cjs-types/server/meta.d.ts.map +1 -1
- package/dist/cjs-types/server/registration.d.ts +10 -0
- package/dist/cjs-types/server/registration.d.ts.map +1 -1
- package/dist/cjs-types/server/schema.d.ts +33 -0
- package/dist/cjs-types/server/schema.d.ts.map +1 -1
- package/dist/cjs-types/server/storage.d.ts.map +1 -1
- package/dist/cjs-types/values/value.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +2935 -2048
- package/dist/cli.bundle.cjs.map +4 -4
- package/dist/esm/bundler/index.js +5 -4
- package/dist/esm/bundler/index.js.map +2 -2
- package/dist/esm/cli/codegen.js +0 -4
- package/dist/esm/cli/codegen.js.map +2 -2
- package/dist/esm/cli/configure.js +12 -4
- package/dist/esm/cli/configure.js.map +2 -2
- package/dist/esm/cli/deploy.js +27 -2
- package/dist/esm/cli/deploy.js.map +2 -2
- package/dist/esm/cli/deploymentSelect.js +6 -3
- package/dist/esm/cli/deploymentSelect.js.map +2 -2
- package/dist/esm/cli/dev.js +6 -0
- package/dist/esm/cli/dev.js.map +2 -2
- package/dist/esm/cli/env.js +11 -6
- package/dist/esm/cli/env.js.map +2 -2
- package/dist/esm/cli/envDefault.js +7 -2
- package/dist/esm/cli/envDefault.js.map +2 -2
- package/dist/esm/cli/lib/api.js +2 -0
- package/dist/esm/cli/lib/api.js.map +2 -2
- package/dist/esm/cli/lib/checkForLargeIndexBackfill.js +95 -0
- package/dist/esm/cli/lib/checkForLargeIndexBackfill.js.map +7 -0
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js +37 -48
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js +63 -41
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js.map +2 -2
- package/dist/esm/cli/lib/checkForStagedValidatorDeletion.js +68 -0
- package/dist/esm/cli/lib/checkForStagedValidatorDeletion.js.map +7 -0
- package/dist/esm/cli/lib/codegen.js.map +2 -2
- package/dist/esm/cli/lib/command.js +2 -1
- package/dist/esm/cli/lib/command.js.map +2 -2
- package/dist/esm/cli/lib/components/definition/bundle.js +37 -11
- package/dist/esm/cli/lib/components/definition/bundle.js.map +2 -2
- package/dist/esm/cli/lib/components.js +55 -5
- package/dist/esm/cli/lib/components.js.map +2 -2
- package/dist/esm/cli/lib/config.js +55 -17
- package/dist/esm/cli/lib/config.js.map +2 -2
- package/dist/esm/cli/lib/deploy2.js +3 -1
- package/dist/esm/cli/lib/deploy2.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js +28 -2
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js.map +2 -2
- package/dist/esm/cli/lib/dev.js +5 -0
- package/dist/esm/cli/lib/dev.js.map +2 -2
- package/dist/esm/cli/lib/formatValidationProgress.js +24 -0
- package/dist/esm/cli/lib/formatValidationProgress.js.map +7 -0
- package/dist/esm/cli/lib/indexes.js.map +1 -1
- package/dist/esm/cli/lib/mcp/tools/env.js +10 -3
- package/dist/esm/cli/lib/mcp/tools/env.js.map +2 -2
- package/dist/esm/cli/lib/run.js +4 -0
- package/dist/esm/cli/lib/run.js.map +2 -2
- package/dist/esm/cli/lib/schemaEvaluation.js +39 -0
- package/dist/esm/cli/lib/schemaEvaluation.js.map +7 -0
- package/dist/esm/cli/lib/usageLimits.js +4 -2
- package/dist/esm/cli/lib/usageLimits.js.map +2 -2
- package/dist/esm/cli/lib/utils/mutex.js +9 -24
- package/dist/esm/cli/lib/utils/mutex.js.map +2 -2
- package/dist/esm/cli/lib/utils/utils.js +47 -18
- package/dist/esm/cli/lib/utils/utils.js.map +2 -2
- package/dist/esm/cli/projectCreate.js +1 -1
- package/dist/esm/cli/projectCreate.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/server/impl/actions_impl.js +7 -3
- package/dist/esm/server/impl/actions_impl.js.map +2 -2
- package/dist/esm/server/impl/storage_impl.js +29 -0
- package/dist/esm/server/impl/storage_impl.js.map +2 -2
- package/dist/esm/server/index.js +4 -1
- package/dist/esm/server/index.js.map +2 -2
- package/dist/esm/server/schema.js +34 -12
- package/dist/esm/server/schema.js.map +2 -2
- package/dist/esm/values/validators.js +1 -1
- package/dist/esm/values/validators.js.map +2 -2
- package/dist/esm/values/value.js +6 -0
- package/dist/esm/values/value.js.map +2 -2
- package/dist/esm-types/bundler/index.d.ts +9 -2
- package/dist/esm-types/bundler/index.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/configure.d.ts +6 -0
- package/dist/esm-types/cli/configure.d.ts.map +1 -1
- package/dist/esm-types/cli/deploy.d.ts +2 -0
- package/dist/esm-types/cli/deploy.d.ts.map +1 -1
- package/dist/esm-types/cli/deploymentCreate.d.ts +6 -6
- package/dist/esm-types/cli/deploymentSelect.d.ts.map +1 -1
- package/dist/esm-types/cli/dev.d.ts +1 -0
- package/dist/esm-types/cli/dev.d.ts.map +1 -1
- package/dist/esm-types/cli/env.d.ts.map +1 -1
- package/dist/esm-types/cli/envDefault.d.ts.map +1 -1
- package/dist/esm-types/cli/generatedApi.d.ts +1 -1
- package/dist/esm-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/api.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForLargeIndexBackfill.d.ts +30 -0
- package/dist/esm-types/cli/lib/checkForLargeIndexBackfill.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts +5 -7
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts +4 -10
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForStagedValidatorDeletion.d.ts +17 -0
- package/dist/esm-types/cli/lib/checkForStagedValidatorDeletion.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/codegen.d.ts +0 -3
- package/dist/esm-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/command.d.ts +2 -0
- package/dist/esm-types/cli/lib/command.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/components/definition/bundle.d.ts +13 -0
- package/dist/esm-types/cli/lib/components/definition/bundle.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/components.d.ts +4 -0
- package/dist/esm-types/cli/lib/components.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/config.d.ts +2 -1
- package/dist/esm-types/cli/lib/config.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deploy2.d.ts +2 -0
- package/dist/esm-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts +460 -16
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/dev.d.ts +1 -0
- package/dist/esm-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/formatValidationProgress.d.ts +8 -0
- package/dist/esm-types/cli/lib/formatValidationProgress.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/mcp/tools/env.d.ts +8 -5
- package/dist/esm-types/cli/lib/mcp/tools/env.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/run.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/schemaEvaluation.d.ts +33 -0
- package/dist/esm-types/cli/lib/schemaEvaluation.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/usageLimits.d.ts +1 -1
- package/dist/esm-types/cli/lib/usageLimits.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/utils/mutex.d.ts +1 -3
- package/dist/esm-types/cli/lib/utils/mutex.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/utils/utils.d.ts +10 -2
- 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/server/impl/actions_impl.d.ts +18 -3
- package/dist/esm-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/storage_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 +63 -0
- package/dist/esm-types/server/meta.d.ts.map +1 -1
- package/dist/esm-types/server/registration.d.ts +10 -0
- package/dist/esm-types/server/registration.d.ts.map +1 -1
- package/dist/esm-types/server/schema.d.ts +33 -0
- package/dist/esm-types/server/schema.d.ts.map +1 -1
- package/dist/esm-types/server/storage.d.ts.map +1 -1
- package/dist/esm-types/values/value.d.ts.map +1 -1
- package/dist/react.bundle.js +7 -1
- package/dist/react.bundle.js.map +2 -2
- package/package.json +5 -5
- package/schemas/convex.schema.json +5 -5
- package/src/bundler/index.ts +9 -4
- package/src/cli/codegen.ts +0 -2
- package/src/cli/configure.ts +27 -7
- package/src/cli/deploy.ts +36 -5
- package/src/cli/deploymentSelect.ts +7 -4
- package/src/cli/dev.ts +9 -0
- package/src/cli/env.ts +12 -6
- package/src/cli/envDefault.ts +8 -2
- package/src/cli/generatedApi.ts +1 -1
- package/src/cli/lib/api.ts +5 -1
- package/src/cli/lib/checkForLargeIndexBackfill.ts +173 -0
- package/src/cli/lib/checkForLargeIndexDeletion.ts +45 -58
- package/src/cli/lib/checkForSlowSchemaValidation.ts +76 -65
- package/src/cli/lib/checkForStagedValidatorDeletion.ts +104 -0
- package/src/cli/lib/codegen.ts +0 -3
- package/src/cli/lib/command.ts +3 -0
- package/src/cli/lib/components/definition/bundle.ts +68 -14
- package/src/cli/lib/components.ts +71 -4
- package/src/cli/lib/config.ts +85 -18
- package/src/cli/lib/deploy2.ts +10 -1
- package/src/cli/lib/deployApi/evaluateSchema.ts +35 -0
- package/src/cli/lib/dev.ts +14 -0
- package/src/cli/lib/formatValidationProgress.ts +35 -0
- package/src/cli/lib/indexes.ts +1 -1
- package/src/cli/lib/mcp/tools/env.ts +17 -3
- package/src/cli/lib/run.ts +2 -0
- package/src/cli/lib/schemaEvaluation.ts +88 -0
- package/src/cli/lib/usageLimits.ts +2 -0
- package/src/cli/lib/utils/mutex.ts +9 -27
- package/src/cli/lib/utils/utils.ts +64 -21
- package/src/cli/projectCreate.ts +1 -1
- package/src/index.ts +1 -1
- package/src/server/impl/actions_impl.ts +26 -6
- package/src/server/impl/storage_impl.ts +30 -0
- package/src/server/index.ts +5 -1
- package/src/server/meta.ts +56 -2
- package/src/server/registration.ts +10 -0
- package/src/server/schema.ts +37 -15
- package/src/server/storage.ts +17 -0
- package/src/values/validators.ts +1 -1
- package/src/values/value.ts +9 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/schema.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Utilities for defining the schema of your Convex project.\n *\n * ## Usage\n *\n * Schemas should be placed in a `schema.ts` file in your `convex/` directory.\n *\n * Schema definitions should be built using {@link defineSchema},\n * {@link defineTable}, and {@link values.v}. Make sure to export the schema as the\n * default export.\n *\n * ```ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * messages: defineTable({\n * body: v.string(),\n * user: v.id(\"users\"),\n * }),\n * users: defineTable({\n * name: v.string(),\n * }),\n * });\n * ```\n *\n * To learn more about schemas, see [Defining a Schema](https://docs.convex.dev/using/schemas).\n * @module\n */\nimport {\n AnyDataModel,\n GenericDataModel,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n TableNamesInDataModel,\n} from \"../server/data_model.js\";\nimport {\n IdField,\n IndexTiebreakerField,\n SystemFields,\n SystemIndexes,\n} from \"../server/system_fields.js\";\nimport { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"../values/index.js\";\nimport {\n GenericValidator,\n ObjectType,\n isValidator,\n v,\n} from \"../values/validator.js\";\nimport {\n VFloat64,\n VId,\n VObject,\n VUnion,\n Validator,\n} from \"../values/validators.js\";\n\n/**\n * Extract all of the index field paths within a {@link Validator}.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof SystemFields;\n\n/**\n * Extract the {@link GenericDocument} within a {@link Validator} and\n * add on the system fields.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractDocument<T extends Validator<any, any, any>> =\n // Add the system fields to `Value` (except `_id` because it depends on\n //the table name) and trick TypeScript into expanding them.\n Expand<SystemFields & T[\"type\"]>;\n\nexport interface DbIndexConfig<\n FirstFieldPath extends string,\n RestFieldPaths extends string[],\n> {\n /**\n * The fields to index, in order. Must specify at least one field.\n */\n fields: [FirstFieldPath, ...RestFieldPaths];\n}\n\n/**\n * The configuration for a full text search index.\n *\n * @public\n */\nexport interface SearchIndexConfig<\n SearchField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for full text search.\n *\n * This must be a field of type `string`.\n */\n searchField: SearchField;\n\n /**\n * Additional fields to index for fast filtering when running search queries.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * The configuration for a vector index.\n *\n * @public\n */\nexport interface VectorIndexConfig<\n VectorField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for vector search.\n *\n * This must be a field of type `v.array(v.float64())` (or a union)\n */\n vectorField: VectorField;\n /**\n * The length of the vectors indexed. This must be between 2 and 2048 inclusive.\n */\n dimensions: number;\n /**\n * Additional fields to index for fast filtering when running vector searches.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * @internal\n */\nexport type VectorIndex = {\n indexDescriptor: string;\n vectorField: string;\n dimensions: number;\n filterFields: string[];\n};\n\n/**\n * @internal\n */\nexport type Index = {\n indexDescriptor: string;\n fields: string[];\n};\n\n/**\n * @internal\n */\nexport type SearchIndex = {\n indexDescriptor: string;\n searchField: string;\n filterFields: string[];\n};\n\n/**\n * Options for defining an index.\n *\n * @public\n */\nexport interface IndexOptions {\n /**\n * Whether the index should be staged.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n */\n staged?: boolean;\n}\n\n/**\n * The definition of a table within a schema.\n *\n * This should be produced by using {@link defineTable}.\n * @public\n */\nexport class TableDefinition<\n DocumentType extends Validator<any, any, any> = Validator<any, any, any>,\n Indexes extends GenericTableIndexes = {},\n SearchIndexes extends GenericTableSearchIndexes = {},\n VectorIndexes extends GenericTableVectorIndexes = {},\n> {\n private indexes: Index[];\n private stagedDbIndexes: Index[];\n private searchIndexes: SearchIndex[];\n private stagedSearchIndexes: SearchIndex[];\n private vectorIndexes: VectorIndex[];\n private stagedVectorIndexes: VectorIndex[];\n // The type of documents stored in this table.\n validator: DocumentType;\n // The proposed next validator for this table, validated against existing\n // documents in the background while `validator` remains enforced.\n private stagedValidator: Validator<any, any, any> | undefined;\n\n /**\n * @internal\n */\n constructor(documentType: DocumentType) {\n this.indexes = [];\n this.stagedDbIndexes = [];\n this.searchIndexes = [];\n this.stagedSearchIndexes = [];\n this.vectorIndexes = [];\n this.stagedVectorIndexes = [];\n this.validator = documentType;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Returns indexes defined on this table.\n * Intended for the advanced use cases of dynamically deciding which index to use for a query.\n * If you think you need this, please chime in on ths issue in the Convex JS GitHub repo.\n * https://github.com/get-convex/convex-js/issues/49\n */\n \" indexes\"(): { indexDescriptor: string; fields: string[] }[] {\n return this.indexes;\n }\n\n /**\n * Define an index on this table.\n *\n * Indexes speed up queries by allowing efficient lookups on specific fields.\n * Use `.withIndex()` in your queries to leverage them.\n *\n * Index fields must be queried in the same order they are defined. If you\n * need to query by `field2` then `field1`, create a separate index with\n * that field order.\n *\n * @example\n * ```ts\n * defineTable({\n * userId: v.id(\"users\"),\n * status: v.string(),\n * updatedAt: v.number(),\n * })\n * // Name indexes after their fields:\n * .index(\"by_userId\", [\"userId\"])\n * .index(\"by_status_updatedAt\", [\"status\", \"updatedAt\"])\n * ```\n *\n * **Best practice:** Always include all index fields in the index name\n * (e.g., `\"by_field1_and_field2\"`).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n *\n * @see https://docs.convex.dev/database/reading-data/indexes\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define an index on this table.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/database/reading-data/indexes).\n *\n * @param name - The name of the index.\n * @param fields - The fields to index, in order. Must specify at least one\n * field.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define a staged index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig:\n | Expand<DbIndexConfig<FirstFieldPath, RestFieldPaths> & IndexOptions>\n | [FirstFieldPath, ...RestFieldPaths],\n ) {\n if (Array.isArray(indexConfig)) {\n // indexConfig is [FirstFieldPath, ...RestFieldPaths]\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig,\n });\n } else if (indexConfig.staged) {\n // indexConfig is object with fields and staged: true\n this.stagedDbIndexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n } else {\n // indexConfig is object with fields (and maybe staged: false/undefined)\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n }\n return this;\n }\n\n /**\n * Define a search index on this table.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n // Update `SearchIndexes` to include the new index and use `Expand` to make\n // the types look pretty in editors.\n Expand<\n SearchIndexes &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes\n >;\n\n /**\n * Define a staged search index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedSearchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.searchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Define a vector index on this table.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n Expand<\n VectorIndexes &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n\n /**\n * Define a staged vector index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedVectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.vectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Stage a new document validator for this table.\n *\n * Convex validates the staged validator against the table's existing\n * documents in the background, while the validator passed to\n * {@link defineTable} remains the one enforced on reads and writes. Once\n * the background validation succeeds, make the staged validator the\n * table's validator and remove `.staged()`.\n *\n * ```ts\n * defineTable({\n * author: v.string(),\n * }).staged({\n * author: v.array(v.string()),\n * })\n * ```\n *\n * TODO: link a worked staged-schema example from the docs once one exists.\n *\n * @param documentSchema - The proposed next type of documents stored in\n * this table, as an object of field validators or a schema validator.\n * @returns A {@link TableDefinition} with the staged validator attached.\n *\n * @internal\n */\n staged(\n documentSchema:\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes> {\n if (this.stagedValidator !== undefined) {\n throw new Error(\"Table cannot have more than one staged validator.\");\n }\n this.stagedValidator = isValidator(documentSchema)\n ? documentSchema\n : v.object(documentSchema);\n return this.self();\n }\n\n /**\n * Work around for https://github.com/microsoft/TypeScript/issues/57035\n */\n protected self(): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n VectorIndexes\n > {\n return this;\n }\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export() {\n const documentType = this.validator.json;\n if (typeof documentType !== \"object\") {\n throw new Error(\n \"Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n\n let stagedDocumentType = undefined;\n if (this.stagedValidator !== undefined) {\n stagedDocumentType = this.stagedValidator.json;\n if (typeof stagedDocumentType !== \"object\") {\n throw new Error(\n \"Invalid staged validator: please make sure that the parameter of `.staged()` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n }\n\n return {\n indexes: this.indexes,\n stagedDbIndexes: this.stagedDbIndexes,\n searchIndexes: this.searchIndexes,\n stagedSearchIndexes: this.stagedSearchIndexes,\n vectorIndexes: this.vectorIndexes,\n stagedVectorIndexes: this.stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }\n}\n\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Validator<Record<string, any>, \"required\", any>,\n>(documentSchema: DocumentSchema): TableDefinition<DocumentSchema>;\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Record<string, GenericValidator>,\n>(\n documentSchema: DocumentSchema,\n): TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>;\nexport function defineTable<\n DocumentSchema extends\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n>(documentSchema: DocumentSchema): TableDefinition<any, any, any> {\n if (isValidator(documentSchema)) {\n return new TableDefinition(documentSchema);\n } else {\n return new TableDefinition(v.object(documentSchema));\n }\n}\n\n/**\n * The validators for the system fields Convex adds to every document.\n *\n * @public\n */\nexport type SystemFieldValidators<TableName extends string> = {\n _id: VId<GenericId<TableName>>;\n _creationTime: VFloat64<number>;\n};\n\n/**\n * Add the system field validators to an object validator, leaving any other\n * validator untouched.\n */\ntype WithSystemFieldValidators<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VObject<infer Type, infer Fields, any, any>\n ? VObject<\n Expand<IdField<TableName> & SystemFields & Type>,\n Expand<SystemFieldValidators<TableName> & Fields>\n >\n : DocumentType;\n\n/**\n * The validator for whole documents of a table: the table's own validator with\n * the `_id` and `_creationTime` system fields added.\n *\n * For a table defined with a union, the system fields are added to each member\n * of the union.\n *\n * @public\n */\nexport type DocValidator<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VUnion<any, infer Members, any, any>\n ? {\n [Index in keyof Members]: WithSystemFieldValidators<\n TableName,\n Members[Index]\n >;\n } extends infer NewMembers extends Validator<any, \"required\", any>[]\n ? VUnion<\n WithSystemFieldValidators<TableName, Members[number]>[\"type\"],\n NewMembers\n >\n : never\n : WithSystemFieldValidators<TableName, DocumentType>;\n\nfunction addSystemFields(\n tableName: string,\n validator: GenericValidator,\n): GenericValidator {\n switch (validator.kind) {\n case \"object\":\n return validator.extend({\n _id: v.id(tableName),\n _creationTime: v.number(),\n });\n case \"union\":\n return v.union(\n ...validator.members.map((member) =>\n addSystemFields(tableName, member),\n ),\n );\n // `v.any()` already permits the system fields.\n case \"any\":\n return validator;\n default:\n throw new Error(\n `Invalid validator for table \"${tableName}\": a table's documents must be objects, or a union of objects (see https://docs.convex.dev/database/schemas)`,\n );\n }\n}\n\n/**\n * Build the validator for whole documents of a table, by adding the `_id` and\n * `_creationTime` system fields to the table's own validator.\n *\n * Prefer {@link SchemaDefinition.doc} when you have the schema in hand: it\n * checks the table name against the schema.\n *\n * @example\n * ```ts\n * const messageDoc = docValidator(\"messages\", schema.tables.messages);\n *\n * export const get = query({\n * args: { id: v.id(\"messages\") },\n * returns: v.union(messageDoc, v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of the table, used for the `_id` validator.\n * @param table - The {@link TableDefinition} for that table.\n * @returns A validator matching documents of the table.\n *\n * @public\n */\nexport function docValidator<\n TableName extends string,\n Table extends TableDefinition<any, any, any, any>,\n>(\n tableName: TableName,\n table: Table,\n): DocValidator<TableName, Table[\"validator\"]> {\n return addSystemFields(tableName, table.validator) as DocValidator<\n TableName,\n Table[\"validator\"]\n >;\n}\n\n/**\n * A type describing the schema of a Convex project.\n *\n * This should be constructed using {@link defineSchema}, {@link defineTable},\n * and {@link v}.\n * @public\n */\nexport type GenericSchema = Record<string, TableDefinition>;\n\nfunction tableInSchema<\n Schema extends GenericSchema,\n TableName extends keyof Schema & string,\n>(\n schema: SchemaDefinition<Schema, boolean>,\n tableName: TableName,\n): Schema[TableName] {\n const table = schema.tables[tableName];\n if (table === undefined) {\n throw new Error(\n `Table \"${tableName}\" is not in this schema. Tables in this schema: ${Object.keys(\n schema.tables,\n ).join(\", \")}`,\n );\n }\n return table;\n}\n\n/**\n *\n * The definition of a Convex project schema.\n *\n * This should be produced by using {@link defineSchema}.\n * @public\n */\nexport class SchemaDefinition<\n Schema extends GenericSchema,\n StrictTableTypes extends boolean,\n> {\n public tables: Schema;\n public strictTableNameTypes!: StrictTableTypes;\n public readonly schemaValidation: boolean;\n\n /**\n * @internal\n */\n constructor(tables: Schema, options?: DefineSchemaOptions<StrictTableTypes>) {\n this.tables = tables;\n this.schemaValidation =\n options?.schemaValidation === undefined ? true : options.schemaValidation;\n }\n\n /**\n * The validator for whole documents of a table in this schema: the table's\n * own validator with the `_id` and `_creationTime` system fields added.\n *\n * @example\n * ```ts\n * export const get = query({\n * args: { id: schema.id(\"messages\") },\n * returns: v.union(schema.doc(\"messages\"), v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching documents of that table.\n */\n doc<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): DocValidator<TableName, Schema[TableName][\"validator\"]> {\n return docValidator(tableName, tableInSchema(this, tableName));\n }\n\n /**\n * The validator for IDs of a table in this schema.\n *\n * Same as `v.id(tableName)`, but only accepts tables in this schema.\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching IDs of that table.\n */\n id<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): VId<GenericId<TableName>> {\n tableInSchema(this, tableName);\n return v.id(tableName);\n }\n\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export(): string {\n return JSON.stringify({\n tables: Object.entries(this.tables).map(([tableName, definition]) => {\n const {\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n } = definition.export();\n return {\n tableName,\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }),\n schemaValidation: this.schemaValidation,\n });\n }\n}\n\n/**\n * Options for {@link defineSchema}.\n *\n * @public\n */\nexport interface DefineSchemaOptions<StrictTableNameTypes extends boolean> {\n /**\n * Whether Convex should validate at runtime that all documents match\n * your schema.\n *\n * If `schemaValidation` is `true`, Convex will:\n * 1. Check that all existing documents match your schema when your schema\n * is pushed.\n * 2. Check that all insertions and updates match your schema during mutations.\n *\n * If `schemaValidation` is `false`, Convex will not validate that new or\n * existing documents match your schema. You'll still get schema-specific\n * TypeScript types, but there will be no validation at runtime that your\n * documents match those types.\n *\n * By default, `schemaValidation` is `true`.\n */\n schemaValidation?: boolean;\n\n /**\n * Whether the TypeScript types should allow accessing tables not in the schema.\n *\n * If `strictTableNameTypes` is `true`, using tables not listed in the schema\n * will generate a TypeScript compilation error.\n *\n * If `strictTableNameTypes` is `false`, you'll be able to access tables not\n * listed in the schema and their document type will be `any`.\n *\n * `strictTableNameTypes: false` is useful for rapid prototyping.\n *\n * Regardless of the value of `strictTableNameTypes`, your schema will only\n * validate documents in the tables listed in the schema. You can still create\n * and modify other tables on the dashboard or in JavaScript mutations.\n *\n * By default, `strictTableNameTypes` is `true`.\n */\n strictTableNameTypes?: StrictTableNameTypes;\n}\n\n/**\n * Define the schema of this Convex project.\n *\n * This should be exported as the default export from a `schema.ts` file in\n * your `convex/` directory. The schema enables runtime validation of documents\n * and provides end-to-end TypeScript type safety.\n *\n * Every document in Convex automatically has two system fields:\n * - `_id` - a unique document ID with validator `v.id(\"tableName\")`\n * - `_creationTime` - a creation timestamp with validator `v.number()`\n *\n * You do not need to include these in your schema definition, they are added\n * automatically.\n *\n * @example\n * ```ts\n * // convex/schema.ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * users: defineTable({\n * name: v.string(),\n * email: v.string(),\n * }).index(\"by_email\", [\"email\"]),\n *\n * messages: defineTable({\n * body: v.string(),\n * userId: v.id(\"users\"),\n * channelId: v.id(\"channels\"),\n * }).index(\"by_channel\", [\"channelId\"]),\n *\n * channels: defineTable({\n * name: v.string(),\n * }),\n *\n * // Discriminated union table:\n * results: defineTable(\n * v.union(\n * v.object({ kind: v.literal(\"error\"), message: v.string() }),\n * v.object({ kind: v.literal(\"success\"), value: v.number() }),\n * )\n * ),\n * });\n * ```\n *\n * **Best practice:** Always include all index fields in the index name. For\n * example, an index on `[\"field1\", \"field2\"]` should be named\n * `\"by_field1_field2\"`.\n *\n * @param schema - A map from table name to {@link TableDefinition} for all of\n * the tables in this project.\n * @param options - Optional configuration. See {@link DefineSchemaOptions} for\n * a full description.\n * @returns The schema.\n *\n * @see https://docs.convex.dev/database/schemas\n * @public\n */\nexport function defineSchema<\n Schema extends GenericSchema,\n StrictTableNameTypes extends boolean = true,\n>(\n schema: Schema,\n options?: DefineSchemaOptions<StrictTableNameTypes>,\n): SchemaDefinition<Schema, StrictTableNameTypes> {\n return new SchemaDefinition(schema, options);\n}\n\n/**\n * Internal type used in Convex code generation!\n *\n * Convert a {@link SchemaDefinition} into a {@link server.GenericDataModel}.\n *\n * @public\n */\nexport type DataModelFromSchemaDefinition<\n SchemaDef extends SchemaDefinition<any, boolean>,\n> = MaybeMakeLooseDataModel<\n {\n [TableName in keyof SchemaDef[\"tables\"] &\n string]: SchemaDef[\"tables\"][TableName] extends TableDefinition<\n infer DocumentType,\n infer Indexes,\n infer SearchIndexes,\n infer VectorIndexes\n >\n ? {\n // We've already added all of the system fields except for `_id`.\n // Add that here.\n document: Expand<IdField<TableName> & ExtractDocument<DocumentType>>;\n fieldPaths:\n | keyof IdField<TableName>\n | ExtractFieldPaths<DocumentType>;\n indexes: Expand<Indexes & SystemIndexes>;\n searchIndexes: SearchIndexes;\n vectorIndexes: VectorIndexes;\n }\n : never;\n },\n SchemaDef[\"strictTableNameTypes\"]\n>;\n\ntype MaybeMakeLooseDataModel<\n DataModel extends GenericDataModel,\n StrictTableNameTypes extends boolean,\n> = StrictTableNameTypes extends true\n ? DataModel\n : Expand<DataModel & AnyDataModel>;\n\nconst _systemSchema = defineSchema({\n _scheduled_functions: defineTable({\n name: v.string(),\n args: v.array(v.any()),\n scheduledTime: v.float64(),\n completedTime: v.optional(v.float64()),\n state: v.union(\n v.object({ kind: v.literal(\"pending\") }),\n v.object({ kind: v.literal(\"inProgress\") }),\n v.object({ kind: v.literal(\"success\") }),\n v.object({ kind: v.literal(\"failed\"), error: v.string() }),\n v.object({ kind: v.literal(\"canceled\") }),\n ),\n }),\n _storage: defineTable({\n sha256: v.string(),\n size: v.float64(),\n contentType: v.optional(v.string()),\n }),\n});\n\nexport interface SystemDataModel extends DataModelFromSchemaDefinition<\n typeof _systemSchema\n> {}\n\nexport type SystemTableNames = TableNamesInDataModel<SystemDataModel>;\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6CA,uBAKO;AA8IA,MAAM,gBAKX;AAAA;AAAA;AAAA;AAAA,EAgBA,YAAY,cAA4B;AAfxC,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AAER;AAAA;AAGA;AAAA;AAAA,wBAAQ;AAMN,SAAK,UAAU,CAAC;AA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AC;AAAA,IACH,OAAO;AACL,WAAK,cAAc,KAAK;AAAA,QACtB,iBAAiB;AAAA,QACjB,aAAa,YAAY;AAAA,QACzB,YAAY,YAAY;AAAA,QACxB,cAAc,YAAY,gBAAgB,CAAC;AAAA,MAC7C,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Utilities for defining the schema of your Convex project.\n *\n * ## Usage\n *\n * Schemas should be placed in a `schema.ts` file in your `convex/` directory.\n *\n * Schema definitions should be built using {@link defineSchema},\n * {@link defineTable}, and {@link values.v}. Make sure to export the schema as the\n * default export.\n *\n * ```ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * messages: defineTable({\n * body: v.string(),\n * user: v.id(\"users\"),\n * }),\n * users: defineTable({\n * name: v.string(),\n * }),\n * });\n * ```\n *\n * To learn more about schemas, see [Defining a Schema](https://docs.convex.dev/using/schemas).\n * @module\n */\nimport {\n AnyDataModel,\n GenericDataModel,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n TableNamesInDataModel,\n} from \"../server/data_model.js\";\nimport {\n IdField,\n IndexTiebreakerField,\n SystemFields,\n SystemIndexes,\n} from \"../server/system_fields.js\";\nimport { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"../values/index.js\";\nimport {\n GenericValidator,\n ObjectType,\n isValidator,\n v,\n} from \"../values/validator.js\";\nimport {\n VFloat64,\n VId,\n VObject,\n VUnion,\n Validator,\n} from \"../values/validators.js\";\n\n/**\n * Extract all of the index field paths within a {@link Validator}.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof SystemFields;\n\n/**\n * Extract the {@link GenericDocument} within a {@link Validator} and\n * add on the system fields.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractDocument<T extends Validator<any, any, any>> =\n // Add the system fields to `Value` (except `_id` because it depends on\n //the table name) and trick TypeScript into expanding them.\n Expand<SystemFields & T[\"type\"]>;\n\nexport interface DbIndexConfig<\n FirstFieldPath extends string,\n RestFieldPaths extends string[],\n> {\n /**\n * The fields to index, in order. Must specify at least one field.\n */\n fields: [FirstFieldPath, ...RestFieldPaths];\n}\n\n/**\n * The configuration for a full text search index.\n *\n * @public\n */\nexport interface SearchIndexConfig<\n SearchField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for full text search.\n *\n * This must be a field of type `string`.\n */\n searchField: SearchField;\n\n /**\n * Additional fields to index for fast filtering when running search queries.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * The configuration for a vector index.\n *\n * @public\n */\nexport interface VectorIndexConfig<\n VectorField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for vector search.\n *\n * This must be a field of type `v.array(v.float64())` (or a union)\n */\n vectorField: VectorField;\n /**\n * The length of the vectors indexed. This must be between 2 and 2048 inclusive.\n */\n dimensions: number;\n /**\n * Additional fields to index for fast filtering when running vector searches.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * @internal\n */\nexport type VectorIndex = {\n indexDescriptor: string;\n vectorField: string;\n dimensions: number;\n filterFields: string[];\n};\n\n/**\n * @internal\n */\nexport type Index = {\n indexDescriptor: string;\n fields: string[];\n};\n\n/**\n * @internal\n */\nexport type SearchIndex = {\n indexDescriptor: string;\n searchField: string;\n filterFields: string[];\n};\n\n/**\n * Options for defining an index.\n *\n * @public\n */\nexport interface IndexOptions {\n /**\n * Whether the index should be staged.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n */\n staged?: boolean;\n}\n\n/**\n * The definition of a table within a schema.\n *\n * This should be produced by using {@link defineTable}.\n * @public\n */\nexport class TableDefinition<\n DocumentType extends Validator<any, any, any> = Validator<any, any, any>,\n Indexes extends GenericTableIndexes = {},\n SearchIndexes extends GenericTableSearchIndexes = {},\n VectorIndexes extends GenericTableVectorIndexes = {},\n> {\n private indexes: Index[];\n private stagedDbIndexes: Index[];\n private searchIndexes: SearchIndex[];\n private stagedSearchIndexes: SearchIndex[];\n private vectorIndexes: VectorIndex[];\n private stagedVectorIndexes: VectorIndex[];\n // The type of documents stored in this table.\n validator: DocumentType;\n // The proposed next validator for this table, validated against existing\n // documents in the background while `validator` remains enforced.\n private stagedValidator: Validator<any, any, any> | undefined;\n\n /**\n * @internal\n */\n constructor(documentType: DocumentType) {\n this.indexes = [];\n this.stagedDbIndexes = [];\n this.searchIndexes = [];\n this.stagedSearchIndexes = [];\n this.vectorIndexes = [];\n this.stagedVectorIndexes = [];\n this.validator = documentType;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Returns indexes defined on this table.\n * Intended for the advanced use cases of dynamically deciding which index to use for a query.\n * If you think you need this, please chime in on ths issue in the Convex JS GitHub repo.\n * https://github.com/get-convex/convex-js/issues/49\n */\n \" indexes\"(): { indexDescriptor: string; fields: string[] }[] {\n return this.indexes;\n }\n\n /**\n * Define an index on this table.\n *\n * Indexes speed up queries by allowing efficient lookups on specific fields.\n * Use `.withIndex()` in your queries to leverage them.\n *\n * Index fields must be queried in the same order they are defined. If you\n * need to query by `field2` then `field1`, create a separate index with\n * that field order.\n *\n * @example\n * ```ts\n * defineTable({\n * userId: v.id(\"users\"),\n * status: v.string(),\n * updatedAt: v.number(),\n * })\n * // Name indexes after their fields:\n * .index(\"by_userId\", [\"userId\"])\n * .index(\"by_status_updatedAt\", [\"status\", \"updatedAt\"])\n * ```\n *\n * **Best practice:** Always include all index fields in the index name\n * (e.g., `\"by_field1_and_field2\"`).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n *\n * @see https://docs.convex.dev/database/reading-data/indexes\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define an index on this table.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/database/reading-data/indexes).\n *\n * @param name - The name of the index.\n * @param fields - The fields to index, in order. Must specify at least one\n * field.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define a staged index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig:\n | Expand<DbIndexConfig<FirstFieldPath, RestFieldPaths> & IndexOptions>\n | [FirstFieldPath, ...RestFieldPaths],\n ) {\n if (Array.isArray(indexConfig)) {\n // indexConfig is [FirstFieldPath, ...RestFieldPaths]\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig,\n });\n } else if (indexConfig.staged) {\n // indexConfig is object with fields and staged: true\n this.stagedDbIndexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n } else {\n // indexConfig is object with fields (and maybe staged: false/undefined)\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n }\n return this;\n }\n\n /**\n * Define a search index on this table.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n // Update `SearchIndexes` to include the new index and use `Expand` to make\n // the types look pretty in editors.\n Expand<\n SearchIndexes &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes\n >;\n\n /**\n * Define a staged search index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedSearchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.searchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Define a vector index on this table.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n Expand<\n VectorIndexes &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n\n /**\n * Define a staged vector index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedVectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.vectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Stage changes to this table's document validator.\n *\n * Convex validates the staged validator against the table's existing\n * documents in the background, while the validator passed to\n * {@link defineTable} remains the one enforced on writes. Once\n * the background validation succeeds, apply the staged changes\n * and remove `.staged()`.\n *\n * For an object validator, pass only the fields to add or replace. Fields\n * omitted from the changes keep their enforced validators.\n * Set a field to `undefined` to remove it from the staged validator.\n * For nested objects, you must specify the full object validator.\n *\n * ```ts\n * defineTable({\n * apple: v.string(),\n * banana: v.number(),\n * legacy: v.optional(v.string()),\n * }).staged({\n * banana: v.union(v.string(), v.number()),\n * legacy: undefined,\n * })\n * ```\n *\n * See [Staged validators](https://docs.convex.dev/database/schemas#staged-validators).\n *\n * @param documentSchema - Field changes for a table defined as an object or\n * `v.any()`, or a full schema validator specifying the proposed next document\n * type. Use a full schema validator for a table defined as a union.\n * @returns A {@link TableDefinition} with the staged validator attached.\n */\n staged(\n documentSchema:\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator | undefined>,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes> {\n if (this.stagedValidator !== undefined) {\n throw new Error(\"Table cannot have more than one staged validator.\");\n }\n if (isValidator(documentSchema)) {\n this.stagedValidator = documentSchema;\n } else {\n if (this.validator.kind !== \"object\" && this.validator.kind !== \"any\") {\n throw new Error(\n \"Specifying top-level field changes is only supported for simple table definitions. For a table defined with a union or record validator, you must stage a fully defined object or union validator.\",\n );\n }\n const enforcedFields =\n this.validator.kind === \"object\" ? this.validator.fields : {};\n const fields: Record<string, GenericValidator> = Object.fromEntries(\n Object.entries({ ...enforcedFields, ...documentSchema }).filter(\n (entry): entry is [string, GenericValidator] =>\n entry[1] !== undefined,\n ),\n );\n this.stagedValidator = v.object(fields);\n }\n return this.self();\n }\n\n /**\n * Work around for https://github.com/microsoft/TypeScript/issues/57035\n */\n protected self(): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n VectorIndexes\n > {\n return this;\n }\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export() {\n const documentType = this.validator.json;\n if (typeof documentType !== \"object\") {\n throw new Error(\n \"Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n\n let stagedDocumentType = undefined;\n if (this.stagedValidator !== undefined) {\n stagedDocumentType = this.stagedValidator.json;\n if (typeof stagedDocumentType !== \"object\") {\n throw new Error(\n \"Invalid staged validator: please make sure that the parameter of `.staged()` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n }\n\n return {\n indexes: this.indexes,\n stagedDbIndexes: this.stagedDbIndexes,\n searchIndexes: this.searchIndexes,\n stagedSearchIndexes: this.stagedSearchIndexes,\n vectorIndexes: this.vectorIndexes,\n stagedVectorIndexes: this.stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }\n}\n\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Validator<Record<string, any>, \"required\", any>,\n>(documentSchema: DocumentSchema): TableDefinition<DocumentSchema>;\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Record<string, GenericValidator>,\n>(\n documentSchema: DocumentSchema,\n): TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>;\nexport function defineTable<\n DocumentSchema extends\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n>(documentSchema: DocumentSchema): TableDefinition<any, any, any> {\n if (isValidator(documentSchema)) {\n return new TableDefinition(documentSchema);\n } else {\n return new TableDefinition(v.object(documentSchema));\n }\n}\n\n/**\n * The validators for the system fields Convex adds to every document.\n *\n * @public\n */\nexport type SystemFieldValidators<TableName extends string> = {\n _id: VId<GenericId<TableName>>;\n _creationTime: VFloat64<number>;\n};\n\n/**\n * Add the system field validators to an object validator, leaving any other\n * validator untouched.\n */\ntype WithSystemFieldValidators<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VObject<infer Type, infer Fields, any, any>\n ? VObject<\n Expand<IdField<TableName> & SystemFields & Type>,\n Expand<SystemFieldValidators<TableName> & Fields>\n >\n : DocumentType;\n\n/**\n * The validator for whole documents of a table: the table's own validator with\n * the `_id` and `_creationTime` system fields added.\n *\n * For a table defined with a union, the system fields are added to each member\n * of the union.\n *\n * @public\n */\nexport type DocValidator<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VUnion<any, infer Members, any, any>\n ? {\n [Index in keyof Members]: WithSystemFieldValidators<\n TableName,\n Members[Index]\n >;\n } extends infer NewMembers extends Validator<any, \"required\", any>[]\n ? VUnion<\n WithSystemFieldValidators<TableName, Members[number]>[\"type\"],\n NewMembers\n >\n : never\n : WithSystemFieldValidators<TableName, DocumentType>;\n\nfunction addSystemFields(\n tableName: string,\n validator: GenericValidator,\n): GenericValidator {\n switch (validator.kind) {\n case \"object\":\n return validator.extend({\n _id: v.id(tableName),\n _creationTime: v.number(),\n });\n case \"union\":\n return v.union(\n ...validator.members.map((member) =>\n addSystemFields(tableName, member),\n ),\n );\n // `v.any()` already permits the system fields.\n case \"any\":\n return validator;\n default:\n throw new Error(\n `Invalid validator for table \"${tableName}\": a table's documents must be objects, or a union of objects (see https://docs.convex.dev/database/schemas)`,\n );\n }\n}\n\n/**\n * Build the validator for whole documents of a table, by adding the `_id` and\n * `_creationTime` system fields to the table's own validator.\n *\n * Prefer {@link SchemaDefinition.doc} when you have the schema in hand: it\n * checks the table name against the schema.\n *\n * @example\n * ```ts\n * const messageDoc = docValidator(\"messages\", schema.tables.messages);\n *\n * export const get = query({\n * args: { id: v.id(\"messages\") },\n * returns: v.union(messageDoc, v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of the table, used for the `_id` validator.\n * @param table - The {@link TableDefinition} for that table.\n * @returns A validator matching documents of the table.\n *\n * @public\n */\nexport function docValidator<\n TableName extends string,\n Table extends TableDefinition<any, any, any, any>,\n>(\n tableName: TableName,\n table: Table,\n): DocValidator<TableName, Table[\"validator\"]> {\n return addSystemFields(tableName, table.validator) as DocValidator<\n TableName,\n Table[\"validator\"]\n >;\n}\n\n/**\n * A type describing the schema of a Convex project.\n *\n * This should be constructed using {@link defineSchema}, {@link defineTable},\n * and {@link v}.\n * @public\n */\nexport type GenericSchema = Record<string, TableDefinition>;\n\nfunction tableInSchema<\n Schema extends GenericSchema,\n TableName extends keyof Schema & string,\n>(\n schema: SchemaDefinition<Schema, boolean>,\n tableName: TableName,\n): Schema[TableName] {\n const table = schema.tables[tableName];\n if (table === undefined) {\n throw new Error(\n `Table \"${tableName}\" is not in this schema. Tables in this schema: ${Object.keys(\n schema.tables,\n ).join(\", \")}`,\n );\n }\n return table;\n}\n\n/**\n *\n * The definition of a Convex project schema.\n *\n * This should be produced by using {@link defineSchema}.\n * @public\n */\nexport class SchemaDefinition<\n Schema extends GenericSchema,\n StrictTableTypes extends boolean,\n> {\n public tables: Schema;\n public strictTableNameTypes!: StrictTableTypes;\n public readonly schemaValidation: boolean;\n\n /**\n * @internal\n */\n constructor(tables: Schema, options?: DefineSchemaOptions<StrictTableTypes>) {\n this.tables = tables;\n this.schemaValidation =\n options?.schemaValidation === undefined ? true : options.schemaValidation;\n }\n\n /**\n * The validator for whole documents of a table in this schema: the table's\n * own validator with the `_id` and `_creationTime` system fields added.\n *\n * @example\n * ```ts\n * export const get = query({\n * args: { id: schema.id(\"messages\") },\n * returns: v.union(schema.doc(\"messages\"), v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching documents of that table.\n */\n doc<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): DocValidator<TableName, Schema[TableName][\"validator\"]> {\n return docValidator(tableName, tableInSchema(this, tableName));\n }\n\n /**\n * The validator for IDs of a table in this schema.\n *\n * Same as `v.id(tableName)`, but only accepts tables in this schema.\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching IDs of that table.\n */\n id<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): VId<GenericId<TableName>> {\n tableInSchema(this, tableName);\n return v.id(tableName);\n }\n\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export(): string {\n return JSON.stringify({\n tables: Object.entries(this.tables).map(([tableName, definition]) => {\n const {\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n } = definition.export();\n return {\n tableName,\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }),\n schemaValidation: this.schemaValidation,\n });\n }\n}\n\n/**\n * Options for {@link defineSchema}.\n *\n * @public\n */\nexport interface DefineSchemaOptions<StrictTableNameTypes extends boolean> {\n /**\n * Whether Convex should validate at runtime that all documents match\n * your schema.\n *\n * If `schemaValidation` is `true`, Convex will:\n * 1. Check that all existing documents match your schema when your schema\n * is pushed.\n * 2. Check that all insertions and updates match your schema during mutations.\n *\n * If `schemaValidation` is `false`, Convex will not validate that new or\n * existing documents match your schema. You'll still get schema-specific\n * TypeScript types, but there will be no validation at runtime that your\n * documents match those types.\n *\n * By default, `schemaValidation` is `true`.\n */\n schemaValidation?: boolean;\n\n /**\n * Whether the TypeScript types should allow accessing tables not in the schema.\n *\n * If `strictTableNameTypes` is `true`, using tables not listed in the schema\n * will generate a TypeScript compilation error.\n *\n * If `strictTableNameTypes` is `false`, you'll be able to access tables not\n * listed in the schema and their document type will be `any`.\n *\n * `strictTableNameTypes: false` is useful for rapid prototyping.\n *\n * Regardless of the value of `strictTableNameTypes`, your schema will only\n * validate documents in the tables listed in the schema. You can still create\n * and modify other tables on the dashboard or in JavaScript mutations.\n *\n * By default, `strictTableNameTypes` is `true`.\n */\n strictTableNameTypes?: StrictTableNameTypes;\n}\n\n/**\n * Define the schema of this Convex project.\n *\n * This should be exported as the default export from a `schema.ts` file in\n * your `convex/` directory. The schema enables runtime validation of documents\n * and provides end-to-end TypeScript type safety.\n *\n * Every document in Convex automatically has two system fields:\n * - `_id` - a unique document ID with validator `v.id(\"tableName\")`\n * - `_creationTime` - a creation timestamp with validator `v.number()`\n *\n * You do not need to include these in your schema definition, they are added\n * automatically.\n *\n * @example\n * ```ts\n * // convex/schema.ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * users: defineTable({\n * name: v.string(),\n * email: v.string(),\n * }).index(\"by_email\", [\"email\"]),\n *\n * messages: defineTable({\n * body: v.string(),\n * userId: v.id(\"users\"),\n * channelId: v.id(\"channels\"),\n * }).index(\"by_channel\", [\"channelId\"]),\n *\n * channels: defineTable({\n * name: v.string(),\n * }),\n *\n * // Discriminated union table:\n * results: defineTable(\n * v.union(\n * v.object({ kind: v.literal(\"error\"), message: v.string() }),\n * v.object({ kind: v.literal(\"success\"), value: v.number() }),\n * )\n * ),\n * });\n * ```\n *\n * **Best practice:** Always include all index fields in the index name. For\n * example, an index on `[\"field1\", \"field2\"]` should be named\n * `\"by_field1_field2\"`.\n *\n * @param schema - A map from table name to {@link TableDefinition} for all of\n * the tables in this project.\n * @param options - Optional configuration. See {@link DefineSchemaOptions} for\n * a full description.\n * @returns The schema.\n *\n * @see https://docs.convex.dev/database/schemas\n * @public\n */\nexport function defineSchema<\n Schema extends GenericSchema,\n StrictTableNameTypes extends boolean = true,\n>(\n schema: Schema,\n options?: DefineSchemaOptions<StrictTableNameTypes>,\n): SchemaDefinition<Schema, StrictTableNameTypes> {\n return new SchemaDefinition(schema, options);\n}\n\n/**\n * Internal type used in Convex code generation!\n *\n * Convert a {@link SchemaDefinition} into a {@link server.GenericDataModel}.\n *\n * @public\n */\nexport type DataModelFromSchemaDefinition<\n SchemaDef extends SchemaDefinition<any, boolean>,\n> = MaybeMakeLooseDataModel<\n {\n [TableName in keyof SchemaDef[\"tables\"] &\n string]: SchemaDef[\"tables\"][TableName] extends TableDefinition<\n infer DocumentType,\n infer Indexes,\n infer SearchIndexes,\n infer VectorIndexes\n >\n ? {\n // We've already added all of the system fields except for `_id`.\n // Add that here.\n document: Expand<IdField<TableName> & ExtractDocument<DocumentType>>;\n fieldPaths:\n | keyof IdField<TableName>\n | ExtractFieldPaths<DocumentType>;\n indexes: Expand<Indexes & SystemIndexes>;\n searchIndexes: SearchIndexes;\n vectorIndexes: VectorIndexes;\n }\n : never;\n },\n SchemaDef[\"strictTableNameTypes\"]\n>;\n\ntype MaybeMakeLooseDataModel<\n DataModel extends GenericDataModel,\n StrictTableNameTypes extends boolean,\n> = StrictTableNameTypes extends true\n ? DataModel\n : Expand<DataModel & AnyDataModel>;\n\nconst _systemSchema = defineSchema({\n _scheduled_functions: defineTable({\n name: v.string(),\n args: v.array(v.any()),\n scheduledTime: v.float64(),\n completedTime: v.optional(v.float64()),\n state: v.union(\n v.object({ kind: v.literal(\"pending\") }),\n v.object({ kind: v.literal(\"inProgress\") }),\n v.object({ kind: v.literal(\"success\") }),\n v.object({ kind: v.literal(\"failed\"), error: v.string() }),\n v.object({ kind: v.literal(\"canceled\") }),\n ),\n }),\n _storage: defineTable({\n sha256: v.string(),\n size: v.float64(),\n contentType: v.optional(v.string()),\n }),\n});\n\nexport interface SystemDataModel extends DataModelFromSchemaDefinition<\n typeof _systemSchema\n> {}\n\nexport type SystemTableNames = TableNamesInDataModel<SystemDataModel>;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6CA,uBAKO;AA8IA,MAAM,gBAKX;AAAA;AAAA;AAAA;AAAA,EAgBA,YAAY,cAA4B;AAfxC,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ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C7C;AA2CA,MAAM,gBAAgB,aAAa;AAAA,EACjC,sBAAsB,YAAY;AAAA,IAChC,MAAM,mBAAE,OAAO;AAAA,IACf,MAAM,mBAAE,MAAM,mBAAE,IAAI,CAAC;AAAA,IACrB,eAAe,mBAAE,QAAQ;AAAA,IACzB,eAAe,mBAAE,SAAS,mBAAE,QAAQ,CAAC;AAAA,IACrC,OAAO,mBAAE;AAAA,MACP,mBAAE,OAAO,EAAE,MAAM,mBAAE,QAAQ,SAAS,EAAE,CAAC;AAAA,MACvC,mBAAE,OAAO,EAAE,MAAM,mBAAE,QAAQ,YAAY,EAAE,CAAC;AAAA,MAC1C,mBAAE,OAAO,EAAE,MAAM,mBAAE,QAAQ,SAAS,EAAE,CAAC;AAAA,MACvC,mBAAE,OAAO,EAAE,MAAM,mBAAE,QAAQ,QAAQ,GAAG,OAAO,mBAAE,OAAO,EAAE,CAAC;AAAA,MACzD,mBAAE,OAAO,EAAE,MAAM,mBAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,IAC1C;AAAA,EACF,CAAC;AAAA,EACD,UAAU,YAAY;AAAA,IACpB,QAAQ,mBAAE,OAAO;AAAA,IACjB,MAAM,mBAAE,QAAQ;AAAA,IAChB,aAAa,mBAAE,SAAS,mBAAE,OAAO,CAAC;AAAA,EACpC,CAAC;AACH,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/storage.ts"],
|
|
4
|
-
"sourcesContent": ["import { GenericId } from \"../values/index.js\";\n\n/**\n * @deprecated This ID format is no longer returned by stable file storage APIs. Use `Id<\"_storage\">` instead.\n *\n * The old ID format used by Convex file storage.\n *\n * \u26A0\uFE0F Security warning: Anyone that has knows to this ID can download the underlying file\n * from `https://<deployment>.convex.cloud/api/storage/<storageId>`.\n * (Note that it\u2019s safe to share the new ID format, `Id<\"_storage\">`, to anyone).\n *\n * @public\n */\nexport type StorageId = string;\n\n/**\n * @deprecated This type is only necessary for backwards compatibility with Convex versions that\n * pre-date `convex@1.6.0`. Use `Id<\"_storage\">` instead.\n */\nexport type FileStorageId = GenericId<\"_storage\"> | StorageId;\n\n/**\n * @deprecated This type is only returned by {@link StorageReader.getUrl | storage.getUrl}.\n * To get the details of a document, use `ctx.db.system.get(\"_storage\", storageId)` instead.\n *\n * Metadata for a single file as returned by {@link StorageReader.getMetadata | storage.getMetadata}.\n *\n * @public\n */\nexport type FileMetadata = {\n /**\n * ID for referencing the file (eg. via {@link StorageReader.getUrl | storage.getUrl})\n *\n * This is an older ID format that is no longer returned by stable file storage APIs.\n * Consider using `Id<\"_storage\">` instead.\n *\n * \u26A0\uFE0F Security warning: Anyone that has knows to this ID can download the underlying file\n * from `https://<deployment>.convex.cloud/api/storage/<storageId>`.\n * (Note that it\u2019s safe to share the new ID format, `Id<\"_storage\">`, to anyone).\n */\n storageId: StorageId;\n /**\n * Hex encoded sha256 checksum of file contents\n */\n sha256: string;\n /**\n * Size of the file in bytes\n */\n size: number;\n /**\n * ContentType of the file if it was provided on upload\n */\n contentType: string | null;\n};\n\n/**\n * An interface to read files from storage within Convex query functions.\n *\n * Available as `ctx.storage` in queries (read-only), mutations, and actions.\n *\n * @example\n * ```typescript\n * // Get a URL for a stored file:\n * const url = await ctx.storage.getUrl(storageId);\n * if (url) {\n * // Use the URL (e.g., return it to the client)\n * }\n *\n * // Get file metadata via the system table (preferred over deprecated getMetadata):\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // metadata: { _id, _creationTime, sha256, size, contentType? }\n * ```\n *\n * @see https://docs.convex.dev/file-storage\n * @public\n */\nexport interface StorageReader {\n /**\n * Get the URL for a file in storage by its `Id<\"_storage\">`.\n *\n * The GET response includes a standard HTTP Digest header with a sha256 checksum.\n *\n * @example\n * ```typescript\n * const url = await ctx.storage.getUrl(storageId);\n * ```\n *\n * @param storageId - The `Id<\"_storage\">` of the file to fetch from Convex storage.\n * @returns - A URL which fetches the file via an HTTP GET, or `null` if the file no longer exists.\n */\n getUrl(storageId: GenericId<\"_storage\">): Promise<string | null>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.getUrl(Id<\"_storage\">)` instead.\n *\n * Get the URL for a file in storage by its {@link StorageId}.\n *\n * The GET response includes a standard HTTP Digest header with a sha256 checksum.\n *\n * @param storageId - The {@link StorageId} of the file to fetch from Convex storage.\n * @returns - A url which fetches the file via an HTTP GET, or `null` if it no longer exists.\n */\n getUrl<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<string | null>;\n\n /**\n * @deprecated Use `ctx.db.system.get(\"_storage\", storageId)` instead, which returns\n * equivalent metadata from the `_storage` system table (with a slightly different shape):\n * ```typescript\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // { _id, _creationTime, sha256, size, contentType? }\n * ```\n *\n * Get metadata for a file.\n *\n * @param storageId - The `Id<\"_storage\">` of the file.\n * @returns - A {@link FileMetadata} object if found or `null` if not found.\n */\n getMetadata(storageId: GenericId<\"_storage\">): Promise<FileMetadata | null>;\n\n /**\n * @deprecated Use `ctx.db.system.get(\"_storage\", storageId)` instead.\n *\n * Get metadata for a file.\n *\n * @param storageId - The {@link StorageId} of the file.\n * @returns - A {@link FileMetadata} object if found or `null` if not found.\n */\n getMetadata<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<FileMetadata | null>;\n}\n\n/**\n * An interface to write files to storage within Convex mutation functions.\n *\n * Available as `ctx.storage` in mutations.\n *\n * @see https://docs.convex.dev/file-storage\n * @public\n */\nexport interface StorageWriter extends StorageReader {\n /**\n * Generate a short-lived URL for uploading a file into storage.\n *\n * The client should make a POST request to this URL with the file as the\n * body. The response will be a JSON object containing a newly allocated\n * `Id<\"_storage\">` (`{ storageId: \"...\" }`).\n *\n * @example\n * ```typescript\n * // In a mutation, generate the upload URL:\n * export const generateUploadUrl = mutation({\n * args: {},\n * returns: v.string(),\n * handler: async (ctx) => {\n * return await ctx.storage.generateUploadUrl();\n * },\n * });\n *\n * // On the client, upload the file:\n * // const uploadUrl = await generateUploadUrl();\n * // const result = await fetch(uploadUrl, { method: \"POST\", body: file });\n * // const { storageId } = await result.json();\n * ```\n *\n * @returns - A short-lived URL for uploading a file via HTTP POST.\n */\n generateUploadUrl(): Promise<string>;\n /**\n * Delete a file from Convex storage.\n *\n * Once a file is deleted, any URLs previously generated by {@link StorageReader.getUrl} will return 404s.\n *\n * @example\n * ```typescript\n * await ctx.storage.delete(storageId);\n * ```\n *\n * @param storageId - The `Id<\"_storage\">` of the file to delete from Convex storage.\n */\n delete(storageId: GenericId<\"_storage\">): Promise<void>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.delete(Id<\"_storage\">)` instead.\n *\n * Delete a file from Convex storage.\n *\n * Once a file is deleted, any URLs previously generated by {@link StorageReader.getUrl} will return 404s.\n *\n * @param storageId - The {@link StorageId} of the file to delete from Convex storage.\n */\n delete<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<void>;\n}\n\n/**\n * An interface to read and write files to storage within Convex actions and HTTP actions.\n *\n * In actions, `ctx.storage` has additional methods not available in mutations:\n * `get()` to download a file as a Blob, and `store()` to upload a Blob directly.\n *\n * @example\n * ```typescript\n * // In an action, download and re-upload a file:\n * const blob = await ctx.storage.get(storageId);\n * if (blob) {\n * const newStorageId = await ctx.storage.store(blob);\n * }\n * ```\n *\n * @public\n */\nexport interface StorageActionWriter extends StorageWriter {\n /**\n * Download a file from storage as a Blob.\n *\n * Only available in actions and HTTP actions (not in mutations or queries).\n *\n * @param storageId - The `Id<\"_storage\">` of the file.\n * @returns A Blob containing the file contents, or `null` if the file doesn't exist.\n */\n get(storageId: GenericId<\"_storage\">): Promise<Blob | null>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.get(Id<\"_storage\">)` instead.\n *\n * Get a Blob containing the file associated with the provided {@link StorageId}, or `null` if there is no file.\n */\n get<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<Blob | null>;\n /**\n * Upload a Blob directly to storage.\n *\n * Only available in actions and HTTP actions. For client-side uploads from\n * mutations, use `generateUploadUrl()` instead.\n *\n * @example\n * ```typescript\n * const storageId = await ctx.storage.store(blob);\n * // Save storageId to the database via ctx.runMutation\n * ```\n *\n * @param blob - The Blob to store.\n * @param options - Optional settings. Pass `sha256` to verify the file integrity.\n * @returns The `Id<\"_storage\">` of the newly stored file.\n */\n store(\n blob: Blob,\n options?: { sha256?: string },\n ): Promise<GenericId<\"_storage\">>;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import { GenericId } from \"../values/index.js\";\n\n/**\n * @deprecated This ID format is no longer returned by stable file storage APIs. Use `Id<\"_storage\">` instead.\n *\n * The old ID format used by Convex file storage.\n *\n * \u26A0\uFE0F Security warning: Anyone that has knows to this ID can download the underlying file\n * from `https://<deployment>.convex.cloud/api/storage/<storageId>`.\n * (Note that it\u2019s safe to share the new ID format, `Id<\"_storage\">`, to anyone).\n *\n * @public\n */\nexport type StorageId = string;\n\n/**\n * @deprecated This type is only necessary for backwards compatibility with Convex versions that\n * pre-date `convex@1.6.0`. Use `Id<\"_storage\">` instead.\n */\nexport type FileStorageId = GenericId<\"_storage\"> | StorageId;\n\n/**\n * @deprecated This type is only returned by {@link StorageReader.getUrl | storage.getUrl}.\n * To get the details of a document, use `ctx.db.system.get(\"_storage\", storageId)` instead.\n *\n * Metadata for a single file as returned by {@link StorageReader.getMetadata | storage.getMetadata}.\n *\n * @public\n */\nexport type FileMetadata = {\n /**\n * ID for referencing the file (eg. via {@link StorageReader.getUrl | storage.getUrl})\n *\n * This is an older ID format that is no longer returned by stable file storage APIs.\n * Consider using `Id<\"_storage\">` instead.\n *\n * \u26A0\uFE0F Security warning: Anyone that has knows to this ID can download the underlying file\n * from `https://<deployment>.convex.cloud/api/storage/<storageId>`.\n * (Note that it\u2019s safe to share the new ID format, `Id<\"_storage\">`, to anyone).\n */\n storageId: StorageId;\n /**\n * Hex encoded sha256 checksum of file contents\n */\n sha256: string;\n /**\n * Size of the file in bytes\n */\n size: number;\n /**\n * ContentType of the file if it was provided on upload\n */\n contentType: string | null;\n};\n\n/**\n * An interface to read files from storage within Convex query functions.\n *\n * Available as `ctx.storage` in queries (read-only), mutations, and actions.\n *\n * @example\n * ```typescript\n * // Get a URL for a stored file:\n * const url = await ctx.storage.getUrl(storageId);\n * if (url) {\n * // Use the URL (e.g., return it to the client)\n * }\n *\n * // Get file metadata via the system table (preferred over deprecated getMetadata):\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // metadata: { _id, _creationTime, sha256, size, contentType? }\n * ```\n *\n * @see https://docs.convex.dev/file-storage\n * @public\n */\nexport interface StorageReader {\n /**\n * Get the URL for a file in storage by its `Id<\"_storage\">`.\n *\n * The GET response includes a standard HTTP Digest header with a sha256 checksum.\n *\n * @example\n * ```typescript\n * const url = await ctx.storage.getUrl(storageId);\n * ```\n *\n * @param storageId - The `Id<\"_storage\">` of the file to fetch from Convex storage.\n * @returns - A URL which fetches the file via an HTTP GET, or `null` if the file no longer exists.\n */\n getUrl(storageId: GenericId<\"_storage\">): Promise<string | null>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.getUrl(Id<\"_storage\">)` instead.\n *\n * Get the URL for a file in storage by its {@link StorageId}.\n *\n * The GET response includes a standard HTTP Digest header with a sha256 checksum.\n *\n * @param storageId - The {@link StorageId} of the file to fetch from Convex storage.\n * @returns - A url which fetches the file via an HTTP GET, or `null` if it no longer exists.\n */\n getUrl<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<string | null>;\n\n /**\n * @deprecated Use `ctx.db.system.get(\"_storage\", storageId)` instead, which returns\n * equivalent metadata from the `_storage` system table (with a slightly different shape):\n * ```typescript\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // { _id, _creationTime, sha256, size, contentType? }\n * ```\n *\n * Get metadata for a file.\n *\n * @param storageId - The `Id<\"_storage\">` of the file.\n * @returns - A {@link FileMetadata} object if found or `null` if not found.\n */\n getMetadata(storageId: GenericId<\"_storage\">): Promise<FileMetadata | null>;\n\n /**\n * @deprecated Use `ctx.db.system.get(\"_storage\", storageId)` instead.\n *\n * Get metadata for a file.\n *\n * @param storageId - The {@link StorageId} of the file.\n * @returns - A {@link FileMetadata} object if found or `null` if not found.\n */\n getMetadata<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<FileMetadata | null>;\n}\n\n/**\n * An interface to write files to storage within Convex mutation functions.\n *\n * Available as `ctx.storage` in mutations.\n *\n * @see https://docs.convex.dev/file-storage\n * @public\n */\nexport interface StorageWriter extends StorageReader {\n /**\n * Generate a short-lived URL for uploading a file into storage.\n *\n * The client should make a POST request to this URL with the file as the\n * body. The response will be a JSON object containing a newly allocated\n * `Id<\"_storage\">` (`{ storageId: \"...\" }`).\n *\n * @example\n * ```typescript\n * // In a mutation, generate the upload URL:\n * export const generateUploadUrl = mutation({\n * args: {},\n * returns: v.string(),\n * handler: async (ctx) => {\n * return await ctx.storage.generateUploadUrl();\n * },\n * });\n *\n * // On the client, upload the file:\n * // const uploadUrl = await generateUploadUrl();\n * // const result = await fetch(uploadUrl, { method: \"POST\", body: file });\n * // const { storageId } = await result.json();\n * ```\n *\n * @returns - A short-lived URL for uploading a file via HTTP POST.\n */\n generateUploadUrl(): Promise<string>;\n /**\n * Delete a file from Convex storage.\n *\n * Once a file is deleted, any URLs previously generated by {@link StorageReader.getUrl} will return 404s.\n *\n * @example\n * ```typescript\n * await ctx.storage.delete(storageId);\n * ```\n *\n * @param storageId - The `Id<\"_storage\">` of the file to delete from Convex storage.\n */\n delete(storageId: GenericId<\"_storage\">): Promise<void>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.delete(Id<\"_storage\">)` instead.\n *\n * Delete a file from Convex storage.\n *\n * Once a file is deleted, any URLs previously generated by {@link StorageReader.getUrl} will return 404s.\n *\n * @param storageId - The {@link StorageId} of the file to delete from Convex storage.\n */\n delete<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<void>;\n\n /**\n * @internal\n */\n // TODO: move `store` from StorageActionWriter to StorageWriter when mutation\n // file storage access is ready for release\n store(\n blob: Blob,\n options?: { sha256?: string },\n ): Promise<GenericId<\"_storage\">>;\n\n /**\n * @internal\n */\n // TODO: move `get` from StorageActionWriter to StorageWriter when mutation\n // file storage access is ready for release\n get(storageId: GenericId<\"_storage\">): Promise<Blob | null>;\n}\n\n/**\n * An interface to read and write files to storage within Convex actions and HTTP actions.\n *\n * In actions, `ctx.storage` has additional methods not available in mutations:\n * `get()` to download a file as a Blob, and `store()` to upload a Blob directly.\n *\n * @example\n * ```typescript\n * // In an action, download and re-upload a file:\n * const blob = await ctx.storage.get(storageId);\n * if (blob) {\n * const newStorageId = await ctx.storage.store(blob);\n * }\n * ```\n *\n * @public\n */\nexport interface StorageActionWriter extends StorageWriter {\n /**\n * Download a file from storage as a Blob.\n *\n * Only available in actions and HTTP actions (not in mutations or queries).\n *\n * @param storageId - The `Id<\"_storage\">` of the file.\n * @returns A Blob containing the file contents, or `null` if the file doesn't exist.\n */\n get(storageId: GenericId<\"_storage\">): Promise<Blob | null>;\n\n /**\n * @deprecated Passing a string is deprecated, use `storage.get(Id<\"_storage\">)` instead.\n *\n * Get a Blob containing the file associated with the provided {@link StorageId}, or `null` if there is no file.\n */\n get<T extends StorageId>(\n storageId: T extends { __tableName: any } ? never : T,\n ): Promise<Blob | null>;\n /**\n * Upload a Blob directly to storage.\n *\n * Only available in actions and HTTP actions. For client-side uploads from\n * mutations, use `generateUploadUrl()` instead.\n *\n * @example\n * ```typescript\n * const storageId = await ctx.storage.store(blob);\n * // Save storageId to the database via ctx.runMutation\n * ```\n *\n * @param blob - The Blob to store.\n * @param options - Optional settings. Pass `sha256` to verify the file integrity.\n * @returns The `Id<\"_storage\">` of the newly stored file.\n */\n store(\n blob: Blob,\n options?: { sha256?: string },\n ): Promise<GenericId<\"_storage\">>;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -505,7 +505,7 @@ class VRecord extends BaseValidator {
|
|
|
505
505
|
throw new Error("Record validator cannot have optional values");
|
|
506
506
|
}
|
|
507
507
|
if (!key.isConvexValidator || !value.isConvexValidator) {
|
|
508
|
-
throw new Error("Key and value of v.record()
|
|
508
|
+
throw new Error("Key and value of v.record() must be validators");
|
|
509
509
|
}
|
|
510
510
|
this.key = key;
|
|
511
511
|
this.value = value;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/values/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport { GenericValidator, ObjectType } from \"./validator.js\";\nimport { CommitTsPlaceholder, JSONValue, convexToJson } from \"./value.js\";\n\ntype TableNameFromType<T> =\n T extends GenericId<infer TableName> ? TableName : string;\n\nconst UNDEFINED_VALIDATOR_ERROR_URL =\n \"https://docs.convex.dev/error#undefined-validator\";\n\nfunction throwUndefinedValidatorError(\n context: string,\n fieldName?: string,\n): never {\n const fieldInfo = fieldName !== undefined ? ` for field \"${fieldName}\"` : \"\";\n throw new Error(\n `A validator is undefined${fieldInfo} in ${context}. ` +\n `This is often caused by circular imports. ` +\n `See ${UNDEFINED_VALIDATOR_ERROR_URL} for details.`,\n );\n}\n\n/**\n * Avoid using `instanceof BaseValidator`; this is inheritence for code reuse\n * not type heirarchy.\n */\nabstract class BaseValidator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> {\n /**\n * Only for TypeScript, the TS type of the JS values validated\n * by this validator.\n */\n readonly type!: Type;\n /**\n * Only for TypeScript, if this an Object validator, then\n * this is the TS type of its property names.\n */\n readonly fieldPaths!: FieldPaths;\n\n /**\n * Whether this is an optional Object property value validator.\n */\n readonly isOptional: IsOptional;\n\n /**\n * Always `\"true\"`.\n */\n readonly isConvexValidator: true;\n\n constructor({ isOptional }: { isOptional: IsOptional }) {\n this.isOptional = isOptional;\n this.isConvexValidator = true;\n }\n /** @internal */\n abstract get json(): ValidatorJSON;\n /** @internal */\n abstract asOptional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n /** Allow this validated field to be absent. */\n abstract optional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n}\n\n/**\n * The type of the `v.id(tableName)` validator.\n */\nexport class VId<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The name of the table that the validated IDs must belong to.\n */\n readonly tableName: TableNameFromType<Type>;\n\n /**\n * The kind of validator, `\"id\"`.\n */\n readonly kind = \"id\" as const;\n\n /**\n * Usually you'd use `v.id(tableName)` instead.\n */\n constructor({\n isOptional,\n tableName,\n }: {\n isOptional: IsOptional;\n tableName: TableNameFromType<Type>;\n }) {\n super({ isOptional });\n if (typeof tableName !== \"string\") {\n throw new Error(\"v.id(tableName) requires a string\");\n }\n this.tableName = tableName;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return { type: \"id\", tableName: this.tableName };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VId<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n tableName: this.tableName,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.float64()` validator.\n */\nexport class VFloat64<\n Type = number,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"float64\"`.\n */\n readonly kind = \"float64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `number` string instead of `float64`.\n return { type: \"number\" };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VFloat64<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.int64()` validator.\n */\nexport class VInt64<\n Type = bigint,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"int64\"`.\n */\n readonly kind = \"int64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `bigint`.\n return { type: \"bigint\" };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VInt64<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.commitTs()` validator.\n */\nexport class VCommitTs<\n Type = bigint | CommitTsPlaceholder,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"commitTs\"`.\n */\n readonly kind = \"commitTs\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VCommitTs<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.boolean()` validator.\n */\nexport class VBoolean<\n Type = boolean,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"boolean\"`.\n */\n readonly kind = \"boolean\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBoolean<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.bytes()` validator.\n */\nexport class VBytes<\n Type = ArrayBuffer,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"bytes\"`.\n */\n readonly kind = \"bytes\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBytes<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.string()` validator.\n */\nexport class VString<\n Type = string,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"string\"`.\n */\n readonly kind = \"string\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VString<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.null()` validator.\n */\nexport class VNull<\n Type = null,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"null\"`.\n */\n readonly kind = \"null\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VNull<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.any()` validator.\n */\nexport class VAny<\n Type = any,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The kind of validator, `\"any\"`.\n */\n readonly kind = \"any\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VAny<Type | undefined, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.object()` validator.\n */\nexport class VObject<\n Type,\n Fields extends Record<string, GenericValidator>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = {\n [Property in keyof Fields]:\n | JoinFieldPaths<Property & string, Fields[Property][\"fieldPaths\"]>\n | Property;\n }[keyof Fields] &\n string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * An object with the validator for each property.\n */\n readonly fields: Fields;\n\n /**\n * The kind of validator, `\"object\"`.\n */\n readonly kind = \"object\" as const;\n\n /**\n * Usually you'd use `v.object({ ... })` instead.\n */\n constructor({\n isOptional,\n fields,\n }: {\n isOptional: IsOptional;\n fields: Fields;\n }) {\n super({ isOptional });\n globalThis.Object.entries(fields).forEach(([fieldName, validator]) => {\n if (validator === undefined) {\n throwUndefinedValidatorError(\"v.object()\", fieldName);\n }\n if (!validator.isConvexValidator) {\n throw new Error(\"v.object() entries must be validators\");\n }\n });\n this.fields = fields;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: globalThis.Object.fromEntries(\n globalThis.Object.entries(this.fields).map(([k, v]) => [\n k,\n {\n fieldType: v.json,\n optional: v.isOptional === \"optional\" ? true : false,\n },\n ]),\n ),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VObject<Type | undefined, Fields, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n fields: this.fields,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n\n /**\n * Create a new VObject with the specified fields omitted.\n * @param fields The field names to omit from this VObject.\n */\n omit<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<Expand<Omit<Type, K>>, Expand<Omit<Fields, K>>, IsOptional> {\n const newFields = { ...this.fields };\n for (const field of fields) {\n delete newFields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as any,\n });\n }\n\n /**\n * Create a new VObject with only the specified fields.\n * @param fields The field names to pick from this VObject.\n */\n pick<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<\n Expand<Pick<Type, Extract<keyof Type, K>>>,\n Expand<Pick<Fields, K>>,\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const field of fields) {\n newFields[field] = this.fields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as Expand<Pick<Fields, K>>,\n });\n }\n\n /**\n * Create a new VObject with all fields marked as optional.\n */\n partial(): VObject<\n { [K in keyof Type]?: Type[K] },\n { [K in keyof Fields]: VOptional<Fields[K]> },\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const [key, validator] of globalThis.Object.entries(this.fields)) {\n newFields[key] = validator.asOptional();\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as {\n [K in keyof Fields]: VOptional<Fields[K]>;\n },\n });\n }\n\n /**\n * Create a new VObject with additional fields merged in.\n * @param fields An object with additional validators to merge into this VObject.\n */\n extend<NewFields extends Record<string, GenericValidator>>(\n fields: NewFields,\n ): VObject<\n Expand<Type & ObjectType<NewFields>>,\n Expand<Fields & NewFields>,\n IsOptional\n > {\n return new VObject({\n isOptional: this.isOptional,\n fields: { ...this.fields, ...fields } as Expand<Fields & NewFields>,\n });\n }\n}\n\n/**\n * The type of the `v.literal()` validator.\n */\nexport class VLiteral<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The value that the validated values must be equal to.\n */\n readonly value: Type;\n\n /**\n * The kind of validator, `\"literal\"`.\n */\n readonly kind = \"literal\" as const;\n\n /**\n * Usually you'd use `v.literal(value)` instead.\n */\n constructor({ isOptional, value }: { isOptional: IsOptional; value: Type }) {\n super({ isOptional });\n if (\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\"\n ) {\n throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n }\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: convexToJson(this.value as string | boolean | number | bigint),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VLiteral<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.array()` validator.\n */\nexport class VArray<\n Type,\n Element extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The validator for the elements of the array.\n */\n readonly element: Element;\n\n /**\n * The kind of validator, `\"array\"`.\n */\n readonly kind = \"array\" as const;\n\n /**\n * Usually you'd use `v.array(element)` instead.\n */\n constructor({\n isOptional,\n element,\n }: {\n isOptional: IsOptional;\n element: Element;\n }) {\n super({ isOptional });\n if (element === undefined) {\n throwUndefinedValidatorError(\"v.array()\");\n }\n this.element = element;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.element.json,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VArray<Type | undefined, Element, \"optional\">({\n isOptional: \"optional\",\n element: this.element,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.record()` validator.\n */\nexport class VRecord<\n Type,\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The validator for the keys of the record.\n */\n readonly key: Key;\n\n /**\n * The validator for the values of the record.\n */\n readonly value: Value;\n\n /**\n * The kind of validator, `\"record\"`.\n */\n readonly kind = \"record\" as const;\n\n /**\n * Usually you'd use `v.record(key, value)` instead.\n */\n constructor({\n isOptional,\n key,\n value,\n }: {\n isOptional: IsOptional;\n key: Key;\n value: Value;\n }) {\n super({ isOptional });\n if (key === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"key\");\n }\n if (value === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"value\");\n }\n if ((key.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional keys\");\n }\n if ((value.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional values\");\n }\n if (!key.isConvexValidator || !value.isConvexValidator) {\n throw new Error(\"Key and value of v.record() but be validators\");\n }\n this.key = key;\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n // This cast is needed because TypeScript thinks the key type is too wide\n keys: this.key.json as RecordKeyValidatorJSON,\n values: {\n fieldType: this.value.json,\n optional: false,\n },\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n key: this.key,\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.union()` validator.\n */\nexport class VUnion<\n Type,\n T extends Validator<any, \"required\", any>[],\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = T[number][\"fieldPaths\"],\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The array of validators, one of which must match the value.\n */\n readonly members: T;\n\n /**\n * The kind of validator, `\"union\"`.\n */\n readonly kind = \"union\" as const;\n\n /**\n * Usually you'd use `v.union(...members)` instead.\n */\n constructor({ isOptional, members }: { isOptional: IsOptional; members: T }) {\n super({ isOptional });\n members.forEach((member, index) => {\n if (member === undefined) {\n throwUndefinedValidatorError(\"v.union()\", `member at index ${index}`);\n }\n if (!member.isConvexValidator) {\n throw new Error(\"All members of v.union() must be validators\");\n }\n });\n this.members = members;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.members.map((v) => v.json),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VUnion<Type | undefined, T, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n members: this.members,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n// prettier-ignore\nexport type VOptional<T extends Validator<any, OptionalProperty, any>> =\n T extends VId<infer Type, OptionalProperty> ? VId<Type | undefined, \"optional\">\n : T extends VString<infer Type, OptionalProperty>\n ? VString<Type | undefined, \"optional\">\n : T extends VFloat64<infer Type, OptionalProperty>\n ? VFloat64<Type | undefined, \"optional\">\n : T extends VInt64<infer Type, OptionalProperty>\n ? VInt64<Type | undefined, \"optional\">\n : T extends VCommitTs<infer Type, OptionalProperty>\n ? VCommitTs<Type | undefined, \"optional\">\n : T extends VBoolean<infer Type, OptionalProperty>\n ? VBoolean<Type | undefined, \"optional\">\n : T extends VNull<infer Type, OptionalProperty>\n ? VNull<Type | undefined, \"optional\">\n : T extends VAny<infer Type, OptionalProperty>\n ? VAny<Type | undefined, \"optional\">\n : T extends VLiteral<infer Type, OptionalProperty>\n ? VLiteral<Type | undefined, \"optional\">\n : T extends VBytes<infer Type, OptionalProperty>\n ? VBytes<Type | undefined, \"optional\">\n : T extends VObject< infer Type, infer Fields, OptionalProperty, infer FieldPaths>\n ? VObject<Type | undefined, Fields, \"optional\", FieldPaths>\n : T extends VArray<infer Type, infer Element, OptionalProperty>\n ? VArray<Type | undefined, Element, \"optional\">\n : T extends VRecord< infer Type, infer Key, infer Value, OptionalProperty, infer FieldPaths>\n ? VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>\n : T extends VUnion<infer Type, infer Members, OptionalProperty, infer FieldPaths>\n ? VUnion<Type | undefined, Members, \"optional\", FieldPaths>\n : never\n\n/**\n * Type representing whether a property in an object is optional or required.\n *\n * @public\n */\nexport type OptionalProperty = \"optional\" | \"required\";\n\n/**\n * A validator for a Convex value.\n *\n * This should be constructed using the validator builder, {@link v}.\n *\n * A validator encapsulates:\n * - The TypeScript type of this value.\n * - Whether this field should be optional if it's included in an object.\n * - The TypeScript type for the set of index field paths that can be used to\n * build indexes on this value.\n * - A JSON representation of the validator.\n *\n * Specific types of validators contain additional information: for example\n * an `ArrayValidator` contains an `element` property with the validator\n * used to validate each element of the list. Use the shared 'kind' property\n * to identity the type of validator.\n *\n * More validators can be added in future releases so an exhaustive\n * switch statement on validator `kind` should be expected to break\n * in future releases of Convex.\n *\n * @public\n */\nexport type Validator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> =\n | VId<Type, IsOptional>\n | VString<Type, IsOptional>\n | VFloat64<Type, IsOptional>\n | VInt64<Type, IsOptional>\n | VCommitTs<Type, IsOptional>\n | VBoolean<Type, IsOptional>\n | VNull<Type, IsOptional>\n | VAny<Type, IsOptional>\n | VLiteral<Type, IsOptional>\n | VBytes<Type, IsOptional>\n | VObject<\n Type,\n Record<string, Validator<any, OptionalProperty, any>>,\n IsOptional,\n FieldPaths\n >\n | VArray<Type, Validator<any, \"required\", any>, IsOptional>\n | VRecord<\n Type,\n Validator<string, \"required\", any>,\n Validator<any, \"required\", any>,\n IsOptional,\n FieldPaths\n >\n | VUnion<Type, Validator<any, \"required\", any>[], IsOptional, FieldPaths>;\n\n/**\n * Join together two index field paths.\n *\n * This is used within the validator builder, {@link v}.\n * @public\n */\nexport type JoinFieldPaths<\n Start extends string,\n End extends string,\n> = `${Start}.${End}`;\n\nexport type ObjectFieldType = { fieldType: ValidatorJSON; optional: boolean };\n\nexport type ValidatorJSON =\n | { type: \"null\" }\n | { type: \"number\" }\n | { type: \"bigint\" }\n | { type: \"commitTs\" }\n | { type: \"boolean\" }\n | { type: \"string\" }\n | { type: \"bytes\" }\n | { type: \"any\" }\n | { type: \"literal\"; value: JSONValue }\n | { type: \"id\"; tableName: string }\n | { type: \"array\"; value: ValidatorJSON }\n | {\n type: \"record\";\n keys: RecordKeyValidatorJSON;\n values: RecordValueValidatorJSON;\n }\n | { type: \"object\"; value: Record<string, ObjectFieldType> }\n | { type: \"union\"; value: ValidatorJSON[] };\n\nexport type RecordKeyValidatorJSON =\n | { type: \"string\" }\n | { type: \"id\"; tableName: string }\n | { type: \"union\"; value: RecordKeyValidatorJSON[] };\n\nexport type RecordValueValidatorJSON = ObjectFieldType & { optional: false };\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAA6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sourcesContent": ["import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport { GenericValidator, ObjectType } from \"./validator.js\";\nimport { CommitTsPlaceholder, JSONValue, convexToJson } from \"./value.js\";\n\ntype TableNameFromType<T> =\n T extends GenericId<infer TableName> ? TableName : string;\n\nconst UNDEFINED_VALIDATOR_ERROR_URL =\n \"https://docs.convex.dev/error#undefined-validator\";\n\nfunction throwUndefinedValidatorError(\n context: string,\n fieldName?: string,\n): never {\n const fieldInfo = fieldName !== undefined ? ` for field \"${fieldName}\"` : \"\";\n throw new Error(\n `A validator is undefined${fieldInfo} in ${context}. ` +\n `This is often caused by circular imports. ` +\n `See ${UNDEFINED_VALIDATOR_ERROR_URL} for details.`,\n );\n}\n\n/**\n * Avoid using `instanceof BaseValidator`; this is inheritence for code reuse\n * not type heirarchy.\n */\nabstract class BaseValidator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> {\n /**\n * Only for TypeScript, the TS type of the JS values validated\n * by this validator.\n */\n readonly type!: Type;\n /**\n * Only for TypeScript, if this an Object validator, then\n * this is the TS type of its property names.\n */\n readonly fieldPaths!: FieldPaths;\n\n /**\n * Whether this is an optional Object property value validator.\n */\n readonly isOptional: IsOptional;\n\n /**\n * Always `\"true\"`.\n */\n readonly isConvexValidator: true;\n\n constructor({ isOptional }: { isOptional: IsOptional }) {\n this.isOptional = isOptional;\n this.isConvexValidator = true;\n }\n /** @internal */\n abstract get json(): ValidatorJSON;\n /** @internal */\n abstract asOptional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n /** Allow this validated field to be absent. */\n abstract optional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n}\n\n/**\n * The type of the `v.id(tableName)` validator.\n */\nexport class VId<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The name of the table that the validated IDs must belong to.\n */\n readonly tableName: TableNameFromType<Type>;\n\n /**\n * The kind of validator, `\"id\"`.\n */\n readonly kind = \"id\" as const;\n\n /**\n * Usually you'd use `v.id(tableName)` instead.\n */\n constructor({\n isOptional,\n tableName,\n }: {\n isOptional: IsOptional;\n tableName: TableNameFromType<Type>;\n }) {\n super({ isOptional });\n if (typeof tableName !== \"string\") {\n throw new Error(\"v.id(tableName) requires a string\");\n }\n this.tableName = tableName;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return { type: \"id\", tableName: this.tableName };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VId<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n tableName: this.tableName,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.float64()` validator.\n */\nexport class VFloat64<\n Type = number,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"float64\"`.\n */\n readonly kind = \"float64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `number` string instead of `float64`.\n return { type: \"number\" };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VFloat64<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.int64()` validator.\n */\nexport class VInt64<\n Type = bigint,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"int64\"`.\n */\n readonly kind = \"int64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `bigint`.\n return { type: \"bigint\" };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VInt64<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.commitTs()` validator.\n */\nexport class VCommitTs<\n Type = bigint | CommitTsPlaceholder,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"commitTs\"`.\n */\n readonly kind = \"commitTs\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VCommitTs<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.boolean()` validator.\n */\nexport class VBoolean<\n Type = boolean,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"boolean\"`.\n */\n readonly kind = \"boolean\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBoolean<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.bytes()` validator.\n */\nexport class VBytes<\n Type = ArrayBuffer,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"bytes\"`.\n */\n readonly kind = \"bytes\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBytes<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.string()` validator.\n */\nexport class VString<\n Type = string,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"string\"`.\n */\n readonly kind = \"string\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VString<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.null()` validator.\n */\nexport class VNull<\n Type = null,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"null\"`.\n */\n readonly kind = \"null\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VNull<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.any()` validator.\n */\nexport class VAny<\n Type = any,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The kind of validator, `\"any\"`.\n */\n readonly kind = \"any\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VAny<Type | undefined, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.object()` validator.\n */\nexport class VObject<\n Type,\n Fields extends Record<string, GenericValidator>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = {\n [Property in keyof Fields]:\n | JoinFieldPaths<Property & string, Fields[Property][\"fieldPaths\"]>\n | Property;\n }[keyof Fields] &\n string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * An object with the validator for each property.\n */\n readonly fields: Fields;\n\n /**\n * The kind of validator, `\"object\"`.\n */\n readonly kind = \"object\" as const;\n\n /**\n * Usually you'd use `v.object({ ... })` instead.\n */\n constructor({\n isOptional,\n fields,\n }: {\n isOptional: IsOptional;\n fields: Fields;\n }) {\n super({ isOptional });\n globalThis.Object.entries(fields).forEach(([fieldName, validator]) => {\n if (validator === undefined) {\n throwUndefinedValidatorError(\"v.object()\", fieldName);\n }\n if (!validator.isConvexValidator) {\n throw new Error(\"v.object() entries must be validators\");\n }\n });\n this.fields = fields;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: globalThis.Object.fromEntries(\n globalThis.Object.entries(this.fields).map(([k, v]) => [\n k,\n {\n fieldType: v.json,\n optional: v.isOptional === \"optional\" ? true : false,\n },\n ]),\n ),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VObject<Type | undefined, Fields, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n fields: this.fields,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n\n /**\n * Create a new VObject with the specified fields omitted.\n * @param fields The field names to omit from this VObject.\n */\n omit<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<Expand<Omit<Type, K>>, Expand<Omit<Fields, K>>, IsOptional> {\n const newFields = { ...this.fields };\n for (const field of fields) {\n delete newFields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as any,\n });\n }\n\n /**\n * Create a new VObject with only the specified fields.\n * @param fields The field names to pick from this VObject.\n */\n pick<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<\n Expand<Pick<Type, Extract<keyof Type, K>>>,\n Expand<Pick<Fields, K>>,\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const field of fields) {\n newFields[field] = this.fields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as Expand<Pick<Fields, K>>,\n });\n }\n\n /**\n * Create a new VObject with all fields marked as optional.\n */\n partial(): VObject<\n { [K in keyof Type]?: Type[K] },\n { [K in keyof Fields]: VOptional<Fields[K]> },\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const [key, validator] of globalThis.Object.entries(this.fields)) {\n newFields[key] = validator.asOptional();\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as {\n [K in keyof Fields]: VOptional<Fields[K]>;\n },\n });\n }\n\n /**\n * Create a new VObject with additional fields merged in.\n * @param fields An object with additional validators to merge into this VObject.\n */\n extend<NewFields extends Record<string, GenericValidator>>(\n fields: NewFields,\n ): VObject<\n Expand<Type & ObjectType<NewFields>>,\n Expand<Fields & NewFields>,\n IsOptional\n > {\n return new VObject({\n isOptional: this.isOptional,\n fields: { ...this.fields, ...fields } as Expand<Fields & NewFields>,\n });\n }\n}\n\n/**\n * The type of the `v.literal()` validator.\n */\nexport class VLiteral<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The value that the validated values must be equal to.\n */\n readonly value: Type;\n\n /**\n * The kind of validator, `\"literal\"`.\n */\n readonly kind = \"literal\" as const;\n\n /**\n * Usually you'd use `v.literal(value)` instead.\n */\n constructor({ isOptional, value }: { isOptional: IsOptional; value: Type }) {\n super({ isOptional });\n if (\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\"\n ) {\n throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n }\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: convexToJson(this.value as string | boolean | number | bigint),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VLiteral<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.array()` validator.\n */\nexport class VArray<\n Type,\n Element extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The validator for the elements of the array.\n */\n readonly element: Element;\n\n /**\n * The kind of validator, `\"array\"`.\n */\n readonly kind = \"array\" as const;\n\n /**\n * Usually you'd use `v.array(element)` instead.\n */\n constructor({\n isOptional,\n element,\n }: {\n isOptional: IsOptional;\n element: Element;\n }) {\n super({ isOptional });\n if (element === undefined) {\n throwUndefinedValidatorError(\"v.array()\");\n }\n this.element = element;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.element.json,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VArray<Type | undefined, Element, \"optional\">({\n isOptional: \"optional\",\n element: this.element,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.record()` validator.\n */\nexport class VRecord<\n Type,\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The validator for the keys of the record.\n */\n readonly key: Key;\n\n /**\n * The validator for the values of the record.\n */\n readonly value: Value;\n\n /**\n * The kind of validator, `\"record\"`.\n */\n readonly kind = \"record\" as const;\n\n /**\n * Usually you'd use `v.record(key, value)` instead.\n */\n constructor({\n isOptional,\n key,\n value,\n }: {\n isOptional: IsOptional;\n key: Key;\n value: Value;\n }) {\n super({ isOptional });\n if (key === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"key\");\n }\n if (value === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"value\");\n }\n if ((key.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional keys\");\n }\n if ((value.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional values\");\n }\n if (!key.isConvexValidator || !value.isConvexValidator) {\n throw new Error(\"Key and value of v.record() must be validators\");\n }\n this.key = key;\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n // This cast is needed because TypeScript thinks the key type is too wide\n keys: this.key.json as RecordKeyValidatorJSON,\n values: {\n fieldType: this.value.json,\n optional: false,\n },\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n key: this.key,\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.union()` validator.\n */\nexport class VUnion<\n Type,\n T extends Validator<any, \"required\", any>[],\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = T[number][\"fieldPaths\"],\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The array of validators, one of which must match the value.\n */\n readonly members: T;\n\n /**\n * The kind of validator, `\"union\"`.\n */\n readonly kind = \"union\" as const;\n\n /**\n * Usually you'd use `v.union(...members)` instead.\n */\n constructor({ isOptional, members }: { isOptional: IsOptional; members: T }) {\n super({ isOptional });\n members.forEach((member, index) => {\n if (member === undefined) {\n throwUndefinedValidatorError(\"v.union()\", `member at index ${index}`);\n }\n if (!member.isConvexValidator) {\n throw new Error(\"All members of v.union() must be validators\");\n }\n });\n this.members = members;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.members.map((v) => v.json),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VUnion<Type | undefined, T, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n members: this.members,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n// prettier-ignore\nexport type VOptional<T extends Validator<any, OptionalProperty, any>> =\n T extends VId<infer Type, OptionalProperty> ? VId<Type | undefined, \"optional\">\n : T extends VString<infer Type, OptionalProperty>\n ? VString<Type | undefined, \"optional\">\n : T extends VFloat64<infer Type, OptionalProperty>\n ? VFloat64<Type | undefined, \"optional\">\n : T extends VInt64<infer Type, OptionalProperty>\n ? VInt64<Type | undefined, \"optional\">\n : T extends VCommitTs<infer Type, OptionalProperty>\n ? VCommitTs<Type | undefined, \"optional\">\n : T extends VBoolean<infer Type, OptionalProperty>\n ? VBoolean<Type | undefined, \"optional\">\n : T extends VNull<infer Type, OptionalProperty>\n ? VNull<Type | undefined, \"optional\">\n : T extends VAny<infer Type, OptionalProperty>\n ? VAny<Type | undefined, \"optional\">\n : T extends VLiteral<infer Type, OptionalProperty>\n ? VLiteral<Type | undefined, \"optional\">\n : T extends VBytes<infer Type, OptionalProperty>\n ? VBytes<Type | undefined, \"optional\">\n : T extends VObject< infer Type, infer Fields, OptionalProperty, infer FieldPaths>\n ? VObject<Type | undefined, Fields, \"optional\", FieldPaths>\n : T extends VArray<infer Type, infer Element, OptionalProperty>\n ? VArray<Type | undefined, Element, \"optional\">\n : T extends VRecord< infer Type, infer Key, infer Value, OptionalProperty, infer FieldPaths>\n ? VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>\n : T extends VUnion<infer Type, infer Members, OptionalProperty, infer FieldPaths>\n ? VUnion<Type | undefined, Members, \"optional\", FieldPaths>\n : never\n\n/**\n * Type representing whether a property in an object is optional or required.\n *\n * @public\n */\nexport type OptionalProperty = \"optional\" | \"required\";\n\n/**\n * A validator for a Convex value.\n *\n * This should be constructed using the validator builder, {@link v}.\n *\n * A validator encapsulates:\n * - The TypeScript type of this value.\n * - Whether this field should be optional if it's included in an object.\n * - The TypeScript type for the set of index field paths that can be used to\n * build indexes on this value.\n * - A JSON representation of the validator.\n *\n * Specific types of validators contain additional information: for example\n * an `ArrayValidator` contains an `element` property with the validator\n * used to validate each element of the list. Use the shared 'kind' property\n * to identity the type of validator.\n *\n * More validators can be added in future releases so an exhaustive\n * switch statement on validator `kind` should be expected to break\n * in future releases of Convex.\n *\n * @public\n */\nexport type Validator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> =\n | VId<Type, IsOptional>\n | VString<Type, IsOptional>\n | VFloat64<Type, IsOptional>\n | VInt64<Type, IsOptional>\n | VCommitTs<Type, IsOptional>\n | VBoolean<Type, IsOptional>\n | VNull<Type, IsOptional>\n | VAny<Type, IsOptional>\n | VLiteral<Type, IsOptional>\n | VBytes<Type, IsOptional>\n | VObject<\n Type,\n Record<string, Validator<any, OptionalProperty, any>>,\n IsOptional,\n FieldPaths\n >\n | VArray<Type, Validator<any, \"required\", any>, IsOptional>\n | VRecord<\n Type,\n Validator<string, \"required\", any>,\n Validator<any, \"required\", any>,\n IsOptional,\n FieldPaths\n >\n | VUnion<Type, Validator<any, \"required\", any>[], IsOptional, FieldPaths>;\n\n/**\n * Join together two index field paths.\n *\n * This is used within the validator builder, {@link v}.\n * @public\n */\nexport type JoinFieldPaths<\n Start extends string,\n End extends string,\n> = `${Start}.${End}`;\n\nexport type ObjectFieldType = { fieldType: ValidatorJSON; optional: boolean };\n\nexport type ValidatorJSON =\n | { type: \"null\" }\n | { type: \"number\" }\n | { type: \"bigint\" }\n | { type: \"commitTs\" }\n | { type: \"boolean\" }\n | { type: \"string\" }\n | { type: \"bytes\" }\n | { type: \"any\" }\n | { type: \"literal\"; value: JSONValue }\n | { type: \"id\"; tableName: string }\n | { type: \"array\"; value: ValidatorJSON }\n | {\n type: \"record\";\n keys: RecordKeyValidatorJSON;\n values: RecordValueValidatorJSON;\n }\n | { type: \"object\"; value: Record<string, ObjectFieldType> }\n | { type: \"union\"; value: ValidatorJSON[] };\n\nexport type RecordKeyValidatorJSON =\n | { type: \"string\" }\n | { type: \"id\"; tableName: string }\n | { type: \"union\"; value: RecordKeyValidatorJSON[] };\n\nexport type RecordValueValidatorJSON = ObjectFieldType & { optional: false };\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAA6D;AAK7D,MAAM,gCACJ;AAEF,SAAS,6BACP,SACA,WACO;AACP,QAAM,YAAY,cAAc,SAAY,eAAe,SAAS,MAAM;AAC1E,QAAM,IAAI;AAAA,IACR,2BAA2B,SAAS,OAAO,OAAO,mDAEzC,6BAA6B;AAAA,EACxC;AACF;AAMA,MAAe,cAIb;AAAA,EAsBA,YAAY,EAAE,WAAW,GAA+B;AAjBxD;AAAA;AAAA;AAAA;AAAA,wBAAS;AAKT;AAAA;AAAA;AAAA;AAAA,wBAAS;AAKT;AAAA;AAAA;AAAA,wBAAS;AAKT;AAAA;AAAA;AAAA,wBAAS;AAGP,SAAK,aAAa;AAClB,SAAK,oBAAoB;AAAA,EAC3B;AAOF;AAKO,MAAM,YAGH,cAAgC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AAM,eAKH,cAA4C;AAAA;AAAA;AAAA;AAAA,EAcpD,YAAY,EAAE,YAAY,QAAQ,GAA2C;AAC3E,UAAM,EAAE,WAAW,CAAC;AAXtB;AAAA;AAAA;AAAA,wBAAS;AAKT;AAAA;AAAA;AAAA,wBAAS,QAAO;AAOd,YAAQ,QAAQ,CAAC,QAAQ,UAAU;AACjC,UAAI,WAAW,QAAW;AACxB,qCAA6B,aAAa,mBAAmB,KAAK,EAAE;AAAA,MACtE;AACA,UAAI,CAAC,OAAO,mBAAmB;AAC7B,cAAM,IAAI,MAAM,6CAA6C;AAAA,MAC/D;AAAA,IACF,CAAC;AACD,SAAK,UAAU;AAAA,EACjB;AAAA;AAAA,EAEA,IAAI,OAAsB;AACxB,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,OAAO,KAAK,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IACvC;AAAA,EACF;AAAA;AAAA,EAEA,WAAW;AACT,WAAO,IAAI,OAAoD;AAAA,MAC7D,YAAY;AAAA,MACZ,SAAS,KAAK;AAAA,IAChB,CAAC;AAAA,EACH;AAAA;AAAA,EAEA,aAAa;AACX,WAAO,KAAK,SAAS;AAAA,EACvB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/values/value.js
CHANGED
|
@@ -228,6 +228,12 @@ function stringifyValueForError(value) {
|
|
|
228
228
|
if (value2 === void 0) {
|
|
229
229
|
return "undefined";
|
|
230
230
|
}
|
|
231
|
+
if (typeof value2 === "function") {
|
|
232
|
+
return "[Function]";
|
|
233
|
+
}
|
|
234
|
+
if (typeof value2 === "symbol") {
|
|
235
|
+
return String(value2);
|
|
236
|
+
}
|
|
231
237
|
if (typeof value2 === "bigint") {
|
|
232
238
|
return `${value2.toString()}n`;
|
|
233
239
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/values/value.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nexport const MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | CommitTsPlaceholder\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nconst COMMIT_TS_UNRESOLVED =\n \"This commit timestamp is unresolved: its value is assigned when the \" +\n \"mutation commits. Read the document after the mutation completes to get \" +\n \"its value.\";\n\n/**\n * The placeholder for a transaction's commit timestamp, which is not known\n * until the mutation commits. Write it into a document field via\n * `db.vars.commitTs` and it resolves to an int64 (`bigint`) at commit,\n * ordered by commit order. Reading the field back within the writing\n * mutation yields the placeholder, which cannot be used as a number.\n *\n * @public\n */\nexport class CommitTsPlaceholder {\n // A private member makes the class nominal: no structurally-similar object\n // type-checks as a placeholder.\n declare private readonly __isCommitTsPlaceholder: undefined;\n [Symbol.toPrimitive](hint: string): string {\n // Allow string conversion so logging a read-back document doesn't throw.\n if (hint === \"string\") {\n return this.toString();\n }\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n valueOf(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toJSON(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toString(): string {\n return \"[unresolved commit timestamp]\";\n }\n}\n\n/**\n * The placeholder for a commit timestamp that is not yet known, exposed as\n * `db.vars.commitTs`. A singleton so that a value read back within the\n * writing mutation compares equal to `db.vars.commitTs`.\n *\n * @internal\n */\nexport const commitTsPlaceholder = new CommitTsPlaceholder();\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$commitTs\") {\n if (value.$commitTs !== null) {\n throw new Error(`Malformed $commitTs field on ${value as any}`);\n }\n return commitTsPlaceholder;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\n\nexport function stringifyValueForError(value: any) {\n const str = JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // By default `JSON.stringify` converts undefined, functions, symbols,\n // Infinity, and NaN to null which produces a confusing error message.\n // We deal with `undefined` specifically because it's the most common.\n // Ideally we'd use a pretty-printing library that prints `undefined`\n // (no quotes), but it might not be worth the bundle size cost.\n return \"undefined\";\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n const rest = \"[...truncated]\";\n let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n const codePoint = str.codePointAt(truncateAt - 1);\n if (codePoint !== undefined && codePoint > 0xffff) {\n // don't split a surrogate pair in half\n truncateAt -= 1;\n }\n return str.substring(0, truncateAt) + rest;\n }\n return str;\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (value instanceof CommitTsPlaceholder) {\n return { $commitTs: null };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,aAAwB;AACxB,oBAA+B;AAE/B,MAAM,gBAAgB;AAEtB,MAAM,YAAY,OAAO,sBAAsB;AACxC,MAAM,YAAY,OAAO,qBAAqB;AACrD,MAAM,OAAO,OAAO,GAAG;AACvB,MAAM,QAAQ,OAAO,GAAG;AACxB,MAAM,cAAc,OAAO,KAAK;AAmEhC,MAAM,uBACJ;AAaK,MAAM,oBAAoB;AAAA,EAI/B,CAAC,OAAO,WAAW,EAAE,MAAsB;AAEzC,QAAI,SAAS,UAAU;AACrB,aAAO,KAAK,SAAS;AAAA,IACvB;AACA,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAAA,EACA,UAAiB;AACf,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAAA,EACA,SAAgB;AACd,UAAM,IAAI,MAAM,oBAAoB;AAAA,EACtC;AAAA,EACA,WAAmB;AACjB,WAAO;A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AW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC1C,wBAAoB,CAAC;AACrB,QAAI,CAAC,IAAI,aAAa,CAAC;AAAA,EACzB;AACA,SAAO;AACT;AAEA,MAAM,0BAA0B;AAEzB,SAAS,uBAAuB,OAAY;AACjD,QAAM,MAAM,KAAK,UAAU,OAAO,CAAC,MAAMA,WAAU;AACjD,QAAIA,WAAU,QAAW;
|
|
4
|
+
"sourcesContent": ["/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nexport const MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | CommitTsPlaceholder\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nconst COMMIT_TS_UNRESOLVED =\n \"This commit timestamp is unresolved: its value is assigned when the \" +\n \"mutation commits. Read the document after the mutation completes to get \" +\n \"its value.\";\n\n/**\n * The placeholder for a transaction's commit timestamp, which is not known\n * until the mutation commits. Write it into a document field via\n * `db.vars.commitTs` and it resolves to an int64 (`bigint`) at commit,\n * ordered by commit order. Reading the field back within the writing\n * mutation yields the placeholder, which cannot be used as a number.\n *\n * @public\n */\nexport class CommitTsPlaceholder {\n // A private member makes the class nominal: no structurally-similar object\n // type-checks as a placeholder.\n declare private readonly __isCommitTsPlaceholder: undefined;\n [Symbol.toPrimitive](hint: string): string {\n // Allow string conversion so logging a read-back document doesn't throw.\n if (hint === \"string\") {\n return this.toString();\n }\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n valueOf(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toJSON(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toString(): string {\n return \"[unresolved commit timestamp]\";\n }\n}\n\n/**\n * The placeholder for a commit timestamp that is not yet known, exposed as\n * `db.vars.commitTs`. A singleton so that a value read back within the\n * writing mutation compares equal to `db.vars.commitTs`.\n *\n * @internal\n */\nexport const commitTsPlaceholder = new CommitTsPlaceholder();\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$commitTs\") {\n if (value.$commitTs !== null) {\n throw new Error(`Malformed $commitTs field on ${value as any}`);\n }\n return commitTsPlaceholder;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\n\nexport function stringifyValueForError(value: any) {\n const str = JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // JSON.stringify omits undefined object properties and converts undefined\n // array elements to null. Preserve them in error messages.\n return \"undefined\";\n }\n if (typeof value === \"function\") {\n // A fixed placeholder also works for functions with custom string coercion.\n return \"[Function]\";\n }\n if (typeof value === \"symbol\") {\n return String(value);\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n const rest = \"[...truncated]\";\n let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n const codePoint = str.codePointAt(truncateAt - 1);\n if (codePoint !== undefined && codePoint > 0xffff) {\n // don't split a surrogate pair in half\n truncateAt -= 1;\n }\n return str.substring(0, truncateAt) + rest;\n }\n return str;\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (value instanceof CommitTsPlaceholder) {\n return { $commitTs: null };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,aAAwB;AACxB,oBAA+B;AAE/B,MAAM,gBAAgB;AAEtB,MAAM,YAAY,OAAO,sBAAsB;AACxC,MAAM,YAAY,OAAO,qBAAqB;AACrD,MAAM,OAAO,OAAO,GAAG;AACvB,MAAM,QAAQ,OAAO,GAAG;AACxB,MAAM,cAAc,OAAO,KAAK;AAmEhC,MAAM,uBACJ;AAaK,MAAM,oBAAoB;AAAA,EAI/B,CAAC,OAAO,WAA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ACF;AAcO,SAAS,aAAa,OAAyB;AACpD,SAAO,qBAAqB,OAAO,OAAO,IAAI,KAAK;AACrD;AAIO,SAAS,wBAAwB,OAAqC;AAC3E,SAAO,gCAAgC,OAAO,OAAO,EAAE;AACzD;AASO,SAAS,iBAAiB,OAAyB;AACxD,SAAO,qBAAqB,OAAO,OAAO,IAAI,IAAI;AACpD;",
|
|
6
6
|
"names": ["value"]
|
|
7
7
|
}
|
|
@@ -36,9 +36,16 @@ export declare function bundle({ ctx, dir, entryPoints, generateSourceMaps, plat
|
|
|
36
36
|
modules: Bundle[];
|
|
37
37
|
externalDependencies: Map<string, string>;
|
|
38
38
|
bundledModuleNames: Set<string>;
|
|
39
|
+
metafile: esbuild.Metafile | null;
|
|
40
|
+
}>;
|
|
41
|
+
export declare function bundleSchema(ctx: Context, dir: string, extraConditions: string[]): Promise<{
|
|
42
|
+
modules: Bundle[];
|
|
43
|
+
metafile: esbuild.Metafile | null;
|
|
44
|
+
}>;
|
|
45
|
+
export declare function bundleAuthConfig(ctx: Context, dir: string): Promise<{
|
|
46
|
+
modules: Bundle[];
|
|
47
|
+
metafile: esbuild.Metafile | null;
|
|
39
48
|
}>;
|
|
40
|
-
export declare function bundleSchema(ctx: Context, dir: string, extraConditions: string[]): Promise<Bundle[]>;
|
|
41
|
-
export declare function bundleAuthConfig(ctx: Context, dir: string): Promise<Bundle[]>;
|
|
42
49
|
export declare function doesImportConvexHttpRouter(source: string): Promise<boolean>;
|
|
43
50
|
export declare function entryPoints(ctx: Context, dir: string): Promise<string[]>;
|
|
44
51
|
export declare const useNodeDirectiveRegex: RegExp;
|