@sanity/cli 6.0.0-alpha.5 → 6.0.0-alpha.7
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/README.md +2907 -109
- package/dist/actions/dataset/create.d.ts +49 -0
- package/dist/actions/dataset/create.js +48 -0
- package/dist/actions/dataset/create.js.map +1 -0
- package/dist/actions/dataset/determineDatasetAclMode.d.ts +37 -0
- package/dist/actions/dataset/determineDatasetAclMode.js +36 -0
- package/dist/actions/dataset/determineDatasetAclMode.js.map +1 -0
- package/dist/actions/debug/gatherDebugInfo.js +15 -21
- package/dist/actions/debug/gatherDebugInfo.js.map +1 -1
- package/dist/actions/debug/types.d.ts +0 -2
- package/dist/actions/debug/types.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +13 -0
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/init/remoteTemplate.js +1 -1
- package/dist/actions/init/remoteTemplate.js.map +1 -1
- package/dist/actions/manifest/extractAppManifest.d.ts +20 -0
- package/dist/actions/manifest/extractAppManifest.js +51 -0
- package/dist/actions/manifest/extractAppManifest.js.map +1 -0
- package/dist/actions/manifest/extractManifest.js +1 -1
- package/dist/actions/manifest/extractManifest.js.map +1 -1
- package/dist/actions/manifest/types.d.ts +6 -1
- package/dist/actions/manifest/types.js.map +1 -1
- package/dist/actions/media/importAspects.js +2 -1
- package/dist/actions/media/importAspects.js.map +1 -1
- package/dist/actions/schema/utils/uniqByProjectIdDataset.d.ts +1 -1
- package/dist/actions/telemetry/resolveConsent.d.ts +1 -9
- package/dist/actions/telemetry/resolveConsent.js +2 -2
- package/dist/actions/telemetry/resolveConsent.js.map +1 -1
- package/dist/actions/telemetry/setConsent.d.ts +1 -4
- package/dist/actions/telemetry/setConsent.js +4 -8
- package/dist/actions/telemetry/setConsent.js.map +1 -1
- package/dist/commands/dataset/create.d.ts +0 -2
- package/dist/commands/dataset/create.js +8 -54
- package/dist/commands/dataset/create.js.map +1 -1
- package/dist/commands/debug.js +5 -9
- package/dist/commands/debug.js.map +1 -1
- package/dist/commands/init.d.ts +6 -1
- package/dist/commands/init.js +358 -20
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/manifest/extract.js +7 -8
- package/dist/commands/manifest/extract.js.map +1 -1
- package/dist/commands/telemetry/disable.js +0 -1
- package/dist/commands/telemetry/disable.js.map +1 -1
- package/dist/commands/telemetry/enable.js +0 -1
- package/dist/commands/telemetry/enable.js.map +1 -1
- package/dist/commands/telemetry/status.js +1 -3
- package/dist/commands/telemetry/status.js.map +1 -1
- package/dist/config/createCliConfig.d.ts +9 -0
- package/dist/hooks/prerun/flushTelemetry.worker.d.ts +2 -0
- package/dist/hooks/prerun/flushTelemetry.worker.js +22 -0
- package/dist/hooks/prerun/flushTelemetry.worker.js.map +1 -0
- package/dist/hooks/prerun/setupTelemetry.js +65 -1
- package/dist/hooks/prerun/setupTelemetry.js.map +1 -1
- package/dist/prompts/init/promptForTypescript.d.ts +2 -0
- package/dist/prompts/init/promptForTypescript.js +15 -0
- package/dist/prompts/init/promptForTypescript.js.map +1 -0
- package/dist/prompts/promptForDatasetAclMode.d.ts +9 -0
- package/dist/prompts/promptForDatasetAclMode.js +27 -0
- package/dist/prompts/promptForDatasetAclMode.js.map +1 -0
- package/dist/prompts/promptForDatasetName.d.ts +1 -1
- package/dist/prompts/promptForDatasetName.js +4 -1
- package/dist/prompts/promptForDatasetName.js.map +1 -1
- package/dist/services/organizations.d.ts +3 -1
- package/dist/services/organizations.js +2 -1
- package/dist/services/organizations.js.map +1 -1
- package/dist/services/telemetry.d.ts +2 -0
- package/dist/services/telemetry.js +20 -0
- package/dist/services/telemetry.js.map +1 -0
- package/dist/services/user.d.ts +5 -0
- package/dist/services/user.js +12 -1
- package/dist/services/user.js.map +1 -1
- package/dist/services/userApplications.d.ts +3 -1
- package/dist/services/userApplications.js +5 -1
- package/dist/services/userApplications.js.map +1 -1
- package/dist/telemetry/cli.telemetry.d.ts +20 -0
- package/dist/telemetry/cli.telemetry.js +8 -0
- package/dist/telemetry/cli.telemetry.js.map +1 -0
- package/dist/telemetry/store/cleanupOldTelemetryFiles.d.ts +5 -0
- package/dist/telemetry/store/cleanupOldTelemetryFiles.js +30 -0
- package/dist/telemetry/store/cleanupOldTelemetryFiles.js.map +1 -0
- package/dist/telemetry/store/createTelemetryStore.d.ts +39 -0
- package/dist/telemetry/store/createTelemetryStore.js +95 -0
- package/dist/telemetry/store/createTelemetryStore.js.map +1 -0
- package/dist/telemetry/store/createTraceId.d.ts +10 -0
- package/dist/telemetry/store/createTraceId.js +10 -0
- package/dist/telemetry/store/createTraceId.js.map +1 -0
- package/dist/telemetry/store/debug.d.ts +5 -0
- package/dist/telemetry/store/debug.js +7 -0
- package/dist/telemetry/store/debug.js.map +1 -0
- package/dist/telemetry/store/findTelemetryFiles.d.ts +13 -0
- package/dist/telemetry/store/findTelemetryFiles.js +34 -0
- package/dist/telemetry/store/findTelemetryFiles.js.map +1 -0
- package/dist/telemetry/store/flushTelemetryFiles.d.ts +20 -0
- package/dist/telemetry/store/flushTelemetryFiles.js +107 -0
- package/dist/telemetry/store/flushTelemetryFiles.js.map +1 -0
- package/dist/telemetry/store/generateTelemetryFilePath.d.ts +17 -0
- package/dist/telemetry/store/generateTelemetryFilePath.js +30 -0
- package/dist/telemetry/store/generateTelemetryFilePath.js.map +1 -0
- package/dist/telemetry/store/getTelemetryBaseInfo.d.ts +27 -0
- package/dist/telemetry/store/getTelemetryBaseInfo.js +34 -0
- package/dist/telemetry/store/getTelemetryBaseInfo.js.map +1 -0
- package/dist/telemetry/store/logger.d.ts +6 -0
- package/dist/telemetry/store/logger.js +54 -0
- package/dist/telemetry/store/logger.js.map +1 -0
- package/dist/telemetry/store/trace.d.ts +6 -0
- package/dist/telemetry/store/trace.js +150 -0
- package/dist/telemetry/store/trace.js.map +1 -0
- package/dist/telemetry/utils/readNDJSON.d.ts +10 -0
- package/dist/telemetry/utils/readNDJSON.js +18 -0
- package/dist/telemetry/utils/readNDJSON.js.map +1 -0
- package/dist/util/detectRuntime.d.ts +8 -0
- package/dist/util/detectRuntime.js +20 -0
- package/dist/util/detectRuntime.js.map +1 -0
- package/dist/util/isStaging.d.ts +7 -0
- package/dist/util/isStaging.js +10 -0
- package/dist/util/isStaging.js.map +1 -0
- package/dist/util/parseArguments.d.ts +35 -0
- package/dist/util/parseArguments.js +42 -0
- package/dist/util/parseArguments.js.map +1 -0
- package/oclif.manifest.json +7 -1
- package/package.json +25 -18
- package/templates/app-quickstart/src/App.css +20 -0
- package/templates/app-quickstart/src/App.tsx +25 -0
- package/templates/app-quickstart/src/ExampleComponent.css +90 -0
- package/templates/app-quickstart/src/ExampleComponent.tsx +37 -0
- package/templates/app-sanity-ui/src/App.tsx +34 -0
- package/templates/app-sanity-ui/src/ExampleComponent.tsx +34 -0
- package/templates/app-sanity-ui/src/SanityUI.tsx +23 -0
- package/templates/blog/README.md +11 -0
- package/templates/blog/schemaTypes/author.js +50 -0
- package/templates/blog/schemaTypes/blockContent.js +67 -0
- package/templates/blog/schemaTypes/category.js +19 -0
- package/templates/blog/schemaTypes/index.js +6 -0
- package/templates/blog/schemaTypes/post.js +65 -0
- package/templates/blog/static/.gitkeep +1 -0
- package/templates/clean/README.md +9 -0
- package/templates/clean/schemaTypes/index.js +1 -0
- package/templates/clean/static/.gitkeep +1 -0
- package/templates/ecommerce/README.md +11 -0
- package/templates/ecommerce/plugins/.gitkeep +1 -0
- package/templates/ecommerce/plugins/barcode-input/BarcodeInput.js +62 -0
- package/templates/ecommerce/plugins/barcode-input/index.js +9 -0
- package/templates/ecommerce/plugins/barcode-input/schemaType.js +60 -0
- package/templates/ecommerce/schemaTypes/blockContent.js +67 -0
- package/templates/ecommerce/schemaTypes/category.js +39 -0
- package/templates/ecommerce/schemaTypes/index.js +23 -0
- package/templates/ecommerce/schemaTypes/locale/localeBlockContent.js +19 -0
- package/templates/ecommerce/schemaTypes/locale/localeString.js +19 -0
- package/templates/ecommerce/schemaTypes/locale/localeText.js +19 -0
- package/templates/ecommerce/schemaTypes/locale/supportedLanguages.js +5 -0
- package/templates/ecommerce/schemaTypes/product.js +83 -0
- package/templates/ecommerce/schemaTypes/productVariant.js +52 -0
- package/templates/ecommerce/schemaTypes/vendor.js +39 -0
- package/templates/ecommerce/static/.gitkeep +1 -0
- package/templates/get-started/README.md +9 -0
- package/templates/get-started/plugins/.gitkeep +1 -0
- package/templates/get-started/plugins/sanity-plugin-tutorial/CustomDefaultLayout.tsx +16 -0
- package/templates/get-started/plugins/sanity-plugin-tutorial/GetStartedTutorial.tsx +104 -0
- package/templates/get-started/plugins/sanity-plugin-tutorial/index.ts +11 -0
- package/templates/get-started/schemaTypes/index.ts +1 -0
- package/templates/get-started/static/.gitkeep +1 -0
- package/templates/moviedb/README.md +10 -0
- package/templates/moviedb/schemaTypes/blockContent.js +67 -0
- package/templates/moviedb/schemaTypes/castMember.js +37 -0
- package/templates/moviedb/schemaTypes/crewMember.js +52 -0
- package/templates/moviedb/schemaTypes/index.js +22 -0
- package/templates/moviedb/schemaTypes/movie.js +85 -0
- package/templates/moviedb/schemaTypes/person.js +37 -0
- package/templates/moviedb/schemaTypes/plotSummaries.js +20 -0
- package/templates/moviedb/schemaTypes/plotSummary.js +24 -0
- package/templates/moviedb/schemaTypes/screening.js +81 -0
- package/templates/moviedb/static/.gitkeep +1 -0
- package/templates/quickstart/README.md +9 -0
- package/templates/quickstart/schemaTypes/index.js +1 -0
- package/templates/quickstart/static/.gitkeep +1 -0
- package/templates/shared/gitignore.txt +29 -0
- package/templates/shared/tsconfig.json +17 -0
- package/templates/shopify/README.md +85 -0
- package/templates/shopify/components/hotspots/ProductTooltip.tsx +38 -0
- package/templates/shopify/components/icons/Shopify.tsx +20 -0
- package/templates/shopify/components/inputs/CollectionHidden.tsx +23 -0
- package/templates/shopify/components/inputs/PlaceholderString.tsx +20 -0
- package/templates/shopify/components/inputs/ProductHidden.tsx +64 -0
- package/templates/shopify/components/inputs/ProductVariantHidden.tsx +24 -0
- package/templates/shopify/components/inputs/ProxyString.tsx +32 -0
- package/templates/shopify/components/media/ColorTheme.tsx +38 -0
- package/templates/shopify/components/media/ShopifyDocumentStatus.tsx +82 -0
- package/templates/shopify/components/studio/Navbar.tsx +29 -0
- package/templates/shopify/constants.ts +61 -0
- package/templates/shopify/docs/features.md +158 -0
- package/templates/shopify/plugins/customDocumentActions/index.ts +55 -0
- package/templates/shopify/plugins/customDocumentActions/shopifyDelete.tsx +144 -0
- package/templates/shopify/plugins/customDocumentActions/shopifyLink.ts +39 -0
- package/templates/shopify/plugins/customDocumentActions/types.ts +14 -0
- package/templates/shopify/schemaTypes/documents/collection.tsx +142 -0
- package/templates/shopify/schemaTypes/documents/colorTheme.tsx +44 -0
- package/templates/shopify/schemaTypes/documents/page.ts +70 -0
- package/templates/shopify/schemaTypes/documents/product.tsx +132 -0
- package/templates/shopify/schemaTypes/documents/productVariant.tsx +67 -0
- package/templates/shopify/schemaTypes/index.ts +108 -0
- package/templates/shopify/schemaTypes/objects/collection/collectionGroupType.ts +27 -0
- package/templates/shopify/schemaTypes/objects/collection/collectionLinksType.ts +16 -0
- package/templates/shopify/schemaTypes/objects/customProductOption/customProductOptionColorObjectType.tsx +48 -0
- package/templates/shopify/schemaTypes/objects/customProductOption/customProductOptionColorType.tsx +50 -0
- package/templates/shopify/schemaTypes/objects/customProductOption/customProductOptionSizeObjectType.ts +40 -0
- package/templates/shopify/schemaTypes/objects/customProductOption/customProductOptionSizeType.ts +49 -0
- package/templates/shopify/schemaTypes/objects/global/footerType.ts +22 -0
- package/templates/shopify/schemaTypes/objects/global/menuLinksType.ts +21 -0
- package/templates/shopify/schemaTypes/objects/global/menuType.ts +17 -0
- package/templates/shopify/schemaTypes/objects/global/notFoundPageType.ts +37 -0
- package/templates/shopify/schemaTypes/objects/hotspot/imageWithProductHotspotsType.ts +48 -0
- package/templates/shopify/schemaTypes/objects/hotspot/productHotspotsType.tsx +17 -0
- package/templates/shopify/schemaTypes/objects/hotspot/spotType.tsx +60 -0
- package/templates/shopify/schemaTypes/objects/link/linkEmailType.tsx +34 -0
- package/templates/shopify/schemaTypes/objects/link/linkExternalType.tsx +37 -0
- package/templates/shopify/schemaTypes/objects/link/linkInternalType.tsx +33 -0
- package/templates/shopify/schemaTypes/objects/link/linkProductType.tsx +60 -0
- package/templates/shopify/schemaTypes/objects/module/accordionGroupType.ts +33 -0
- package/templates/shopify/schemaTypes/objects/module/accordionType.ts +28 -0
- package/templates/shopify/schemaTypes/objects/module/callToActionType.tsx +85 -0
- package/templates/shopify/schemaTypes/objects/module/calloutType.ts +38 -0
- package/templates/shopify/schemaTypes/objects/module/collectionReferenceType.tsx +47 -0
- package/templates/shopify/schemaTypes/objects/module/gridItemType.ts +41 -0
- package/templates/shopify/schemaTypes/objects/module/gridType.ts +28 -0
- package/templates/shopify/schemaTypes/objects/module/heroType.tsx +40 -0
- package/templates/shopify/schemaTypes/objects/module/imageCallToActionType.tsx +19 -0
- package/templates/shopify/schemaTypes/objects/module/imageFeatureType.ts +80 -0
- package/templates/shopify/schemaTypes/objects/module/imageFeaturesType.tsx +51 -0
- package/templates/shopify/schemaTypes/objects/module/instagramType.ts +35 -0
- package/templates/shopify/schemaTypes/objects/module/productFeaturesType.tsx +50 -0
- package/templates/shopify/schemaTypes/objects/module/productReferenceType.tsx +42 -0
- package/templates/shopify/schemaTypes/objects/seoType.ts +31 -0
- package/templates/shopify/schemaTypes/objects/shopify/collectionRuleType.tsx +37 -0
- package/templates/shopify/schemaTypes/objects/shopify/inventoryType.ts +25 -0
- package/templates/shopify/schemaTypes/objects/shopify/optionType.tsx +31 -0
- package/templates/shopify/schemaTypes/objects/shopify/placeholderStringType.ts +11 -0
- package/templates/shopify/schemaTypes/objects/shopify/priceRangeType.ts +20 -0
- package/templates/shopify/schemaTypes/objects/shopify/productWithVariantType.tsx +142 -0
- package/templates/shopify/schemaTypes/objects/shopify/proxyStringType.ts +12 -0
- package/templates/shopify/schemaTypes/objects/shopify/shopType.ts +15 -0
- package/templates/shopify/schemaTypes/objects/shopify/shopifyCollectionType.ts +84 -0
- package/templates/shopify/schemaTypes/objects/shopify/shopifyProductType.ts +131 -0
- package/templates/shopify/schemaTypes/objects/shopify/shopifyProductVariantType.ts +121 -0
- package/templates/shopify/schemaTypes/portableText/portableTextSimpleType.tsx +45 -0
- package/templates/shopify/schemaTypes/portableText/portableTextType.tsx +52 -0
- package/templates/shopify/schemaTypes/singletons/homeType.ts +49 -0
- package/templates/shopify/schemaTypes/singletons/settingsType.ts +96 -0
- package/templates/shopify/static/.gitkeep +1 -0
- package/templates/shopify/structure/collectionStructure.ts +9 -0
- package/templates/shopify/structure/colorThemeStructure.ts +9 -0
- package/templates/shopify/structure/homeStructure.ts +9 -0
- package/templates/shopify/structure/index.ts +57 -0
- package/templates/shopify/structure/pageStructure.ts +11 -0
- package/templates/shopify/structure/productStructure.ts +51 -0
- package/templates/shopify/structure/settingStructure.ts +9 -0
- package/templates/shopify/utils/blocksToText.ts +20 -0
- package/templates/shopify/utils/defineStructure.ts +11 -0
- package/templates/shopify/utils/getPriceRange.ts +24 -0
- package/templates/shopify/utils/shopifyUrls.ts +22 -0
- package/templates/shopify/utils/validateSlug.ts +18 -0
- package/templates/shopify-online-storefront/README.md +54 -0
- package/templates/shopify-online-storefront/components/icons/Shopify.tsx +22 -0
- package/templates/shopify-online-storefront/components/inputs/CollectionHidden.tsx +23 -0
- package/templates/shopify-online-storefront/components/inputs/PlaceholderString.tsx +25 -0
- package/templates/shopify-online-storefront/components/inputs/ProductHidden.tsx +66 -0
- package/templates/shopify-online-storefront/components/inputs/ProductVariantHidden.tsx +25 -0
- package/templates/shopify-online-storefront/components/inputs/ProxyString.tsx +38 -0
- package/templates/shopify-online-storefront/components/media/ShopifyDocumentStatus.tsx +83 -0
- package/templates/shopify-online-storefront/constants.ts +18 -0
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/index.ts +45 -0
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/shopifyDelete.tsx +144 -0
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/shopifyLink.ts +39 -0
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/types.ts +14 -0
- package/templates/shopify-online-storefront/schemaTypes/blocks/blockContent.ts +32 -0
- package/templates/shopify-online-storefront/schemaTypes/documents/collection.tsx +83 -0
- package/templates/shopify-online-storefront/schemaTypes/documents/product.tsx +102 -0
- package/templates/shopify-online-storefront/schemaTypes/documents/productVariant.tsx +82 -0
- package/templates/shopify-online-storefront/schemaTypes/index.ts +43 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/accordion.ts +31 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/accordionGroup.ts +35 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/callout.ts +40 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/inventory.ts +30 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/option.ts +30 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/priceRange.ts +22 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/proxyString.ts +11 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/shopifyCollection.ts +109 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/shopifyCollectionRule.tsx +45 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/shopifyProduct.ts +165 -0
- package/templates/shopify-online-storefront/schemaTypes/objects/shopifyProductVariant.ts +151 -0
- package/templates/shopify-online-storefront/structure/collectionStructure.ts +9 -0
- package/templates/shopify-online-storefront/structure/index.ts +37 -0
- package/templates/shopify-online-storefront/structure/productStructure.ts +35 -0
- package/templates/shopify-online-storefront/utils/defineStructure.ts +11 -0
- package/templates/shopify-online-storefront/utils/getPriceRange.ts +24 -0
- package/templates/shopify-online-storefront/utils/shopifyUrls.ts +22 -0
- package/dist/actions/build/__tests__/buildApp.test.js +0 -367
- package/dist/actions/build/__tests__/buildApp.test.js.map +0 -1
- package/dist/actions/build/__tests__/buildStudio.test.js +0 -561
- package/dist/actions/build/__tests__/buildStudio.test.js.map +0 -1
- package/dist/actions/build/__tests__/checkRequiredDependencies.test.js +0 -233
- package/dist/actions/build/__tests__/checkRequiredDependencies.test.js.map +0 -1
- package/dist/actions/build/__tests__/checkStudioDependencyVersions.test.js +0 -414
- package/dist/actions/build/__tests__/checkStudioDependencyVersions.test.js.map +0 -1
- package/dist/actions/build/__tests__/determineBasePath.test.js +0 -24
- package/dist/actions/build/__tests__/determineBasePath.test.js.map +0 -1
- package/dist/actions/build/__tests__/getAutoUpdatesImportMap.test.js +0 -109
- package/dist/actions/build/__tests__/getAutoUpdatesImportMap.test.js.map +0 -1
- package/dist/actions/build/__tests__/getViteConfig.test.js +0 -493
- package/dist/actions/build/__tests__/getViteConfig.test.js.map +0 -1
- package/dist/actions/build/__tests__/renderDocument.test.js +0 -278
- package/dist/actions/build/__tests__/renderDocument.test.js.map +0 -1
- package/dist/actions/build/__tests__/shouldAutoUpdate.test.js +0 -153
- package/dist/actions/build/__tests__/shouldAutoUpdate.test.js.map +0 -1
- package/dist/actions/build/renderDocumentWorker/__tests__/renderDocumentWorker.test.js +0 -657
- package/dist/actions/build/renderDocumentWorker/__tests__/renderDocumentWorker.test.js.map +0 -1
- package/dist/actions/dataset/__tests__/validateDatasetName.test.js +0 -182
- package/dist/actions/dataset/__tests__/validateDatasetName.test.js.map +0 -1
- package/dist/actions/deploy/__tests__/checkDir.test.js +0 -120
- package/dist/actions/deploy/__tests__/checkDir.test.js.map +0 -1
- package/dist/actions/docs/__tests__/normalizeDocsPath.test.js +0 -16
- package/dist/actions/docs/__tests__/normalizeDocsPath.test.js.map +0 -1
- package/dist/actions/documents/validation/reporters/prettyReporter/__tests__/formatDocumentValidation.test.js +0 -124
- package/dist/actions/documents/validation/reporters/prettyReporter/__tests__/formatDocumentValidation.test.js.map +0 -1
- package/dist/actions/graphql/__tests__/getGraphQLAPIs.test.js +0 -274
- package/dist/actions/graphql/__tests__/getGraphQLAPIs.test.js.map +0 -1
- package/dist/actions/media/__tests__/importMedia.test.js +0 -182
- package/dist/actions/media/__tests__/importMedia.test.js.map +0 -1
- package/dist/actions/schema/__tests__/formatSchemaValidation.test.js +0 -174
- package/dist/actions/schema/__tests__/formatSchemaValidation.test.js.map +0 -1
- package/dist/actions/schema/__tests__/validateAction.test.js +0 -281
- package/dist/actions/schema/__tests__/validateAction.test.js.map +0 -1
- package/dist/actions/telemetry/__tests__/fetchTelemetryConsent.test.js +0 -27
- package/dist/actions/telemetry/__tests__/fetchTelemetryConsent.test.js.map +0 -1
- package/dist/actions/users/__tests__/validateEmail.test.js +0 -16
- package/dist/actions/users/__tests__/validateEmail.test.js.map +0 -1
- package/dist/commands/__tests__/blueprints.test.js +0 -54
- package/dist/commands/__tests__/blueprints.test.js.map +0 -1
- package/dist/commands/__tests__/build.test.js +0 -132
- package/dist/commands/__tests__/build.test.js.map +0 -1
- package/dist/commands/__tests__/codemod.test.js +0 -271
- package/dist/commands/__tests__/codemod.test.js.map +0 -1
- package/dist/commands/__tests__/debug.test.js +0 -590
- package/dist/commands/__tests__/debug.test.js.map +0 -1
- package/dist/commands/__tests__/deploy.test.js +0 -1945
- package/dist/commands/__tests__/deploy.test.js.map +0 -1
- package/dist/commands/__tests__/dev.test.js +0 -453
- package/dist/commands/__tests__/dev.test.js.map +0 -1
- package/dist/commands/__tests__/exec.test.js +0 -207
- package/dist/commands/__tests__/exec.test.js.map +0 -1
- package/dist/commands/__tests__/init/init.authentication.test.js +0 -73
- package/dist/commands/__tests__/init/init.authentication.test.js.map +0 -1
- package/dist/commands/__tests__/init/init.create-new-project.test.js +0 -195
- package/dist/commands/__tests__/init/init.create-new-project.test.js.map +0 -1
- package/dist/commands/__tests__/init/init.plan.test.js +0 -279
- package/dist/commands/__tests__/init/init.plan.test.js.map +0 -1
- package/dist/commands/__tests__/init/init.setup.test.js +0 -335
- package/dist/commands/__tests__/init/init.setup.test.js.map +0 -1
- package/dist/commands/__tests__/install.test.js +0 -282
- package/dist/commands/__tests__/install.test.js.map +0 -1
- package/dist/commands/__tests__/learn.test.js +0 -29
- package/dist/commands/__tests__/learn.test.js.map +0 -1
- package/dist/commands/__tests__/logout.test.js +0 -91
- package/dist/commands/__tests__/logout.test.js.map +0 -1
- package/dist/commands/__tests__/manage.test.js +0 -110
- package/dist/commands/__tests__/manage.test.js.map +0 -1
- package/dist/commands/__tests__/migration.test.js +0 -119
- package/dist/commands/__tests__/migration.test.js.map +0 -1
- package/dist/commands/__tests__/preview.test.js +0 -261
- package/dist/commands/__tests__/preview.test.js.map +0 -1
- package/dist/commands/__tests__/start.test.js +0 -253
- package/dist/commands/__tests__/start.test.js.map +0 -1
- package/dist/commands/__tests__/undeploy.test.js +0 -382
- package/dist/commands/__tests__/undeploy.test.js.map +0 -1
- package/dist/commands/__tests__/versions.test.js +0 -142
- package/dist/commands/__tests__/versions.test.js.map +0 -1
- package/dist/commands/backup/__tests__/disable.test.js +0 -204
- package/dist/commands/backup/__tests__/disable.test.js.map +0 -1
- package/dist/commands/backup/__tests__/download.test.js +0 -768
- package/dist/commands/backup/__tests__/download.test.js.map +0 -1
- package/dist/commands/backup/__tests__/enable.test.js +0 -286
- package/dist/commands/backup/__tests__/enable.test.js.map +0 -1
- package/dist/commands/backup/__tests__/list.test.js +0 -330
- package/dist/commands/backup/__tests__/list.test.js.map +0 -1
- package/dist/commands/cors/__tests__/add.test.js +0 -376
- package/dist/commands/cors/__tests__/add.test.js.map +0 -1
- package/dist/commands/cors/__tests__/delete.test.js +0 -308
- package/dist/commands/cors/__tests__/delete.test.js.map +0 -1
- package/dist/commands/cors/__tests__/list.test.js +0 -241
- package/dist/commands/cors/__tests__/list.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/copy.test.js +0 -628
- package/dist/commands/dataset/__tests__/copy.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/create.test.js +0 -342
- package/dist/commands/dataset/__tests__/create.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/delete.test.js +0 -231
- package/dist/commands/dataset/__tests__/delete.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/export.test.js +0 -601
- package/dist/commands/dataset/__tests__/export.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/import.test.js +0 -53
- package/dist/commands/dataset/__tests__/import.test.js.map +0 -1
- package/dist/commands/dataset/__tests__/list.test.js +0 -216
- package/dist/commands/dataset/__tests__/list.test.js.map +0 -1
- package/dist/commands/dataset/alias/__tests__/create.test.js +0 -339
- package/dist/commands/dataset/alias/__tests__/create.test.js.map +0 -1
- package/dist/commands/dataset/alias/__tests__/delete.test.js +0 -247
- package/dist/commands/dataset/alias/__tests__/delete.test.js.map +0 -1
- package/dist/commands/dataset/alias/__tests__/link.test.js +0 -376
- package/dist/commands/dataset/alias/__tests__/link.test.js.map +0 -1
- package/dist/commands/dataset/alias/__tests__/unlink.test.js +0 -313
- package/dist/commands/dataset/alias/__tests__/unlink.test.js.map +0 -1
- package/dist/commands/dataset/visibility/__tests__/get.test.js +0 -128
- package/dist/commands/dataset/visibility/__tests__/get.test.js.map +0 -1
- package/dist/commands/dataset/visibility/__tests__/set.test.js +0 -198
- package/dist/commands/dataset/visibility/__tests__/set.test.js.map +0 -1
- package/dist/commands/docs/__tests__/browse.test.js +0 -29
- package/dist/commands/docs/__tests__/browse.test.js.map +0 -1
- package/dist/commands/docs/__tests__/read.test.js +0 -78
- package/dist/commands/docs/__tests__/read.test.js.map +0 -1
- package/dist/commands/docs/__tests__/search.test.js +0 -255
- package/dist/commands/docs/__tests__/search.test.js.map +0 -1
- package/dist/commands/documents/__tests__/create.test.js +0 -1030
- package/dist/commands/documents/__tests__/create.test.js.map +0 -1
- package/dist/commands/documents/__tests__/delete.test.js +0 -300
- package/dist/commands/documents/__tests__/delete.test.js.map +0 -1
- package/dist/commands/documents/__tests__/get.test.js +0 -182
- package/dist/commands/documents/__tests__/get.test.js.map +0 -1
- package/dist/commands/documents/__tests__/query.test.js +0 -300
- package/dist/commands/documents/__tests__/query.test.js.map +0 -1
- package/dist/commands/documents/__tests__/validate.test.js +0 -249
- package/dist/commands/documents/__tests__/validate.test.js.map +0 -1
- package/dist/commands/graphql/__tests__/list.test.js +0 -240
- package/dist/commands/graphql/__tests__/list.test.js.map +0 -1
- package/dist/commands/graphql/__tests__/undeploy.test.js +0 -410
- package/dist/commands/graphql/__tests__/undeploy.test.js.map +0 -1
- package/dist/commands/hook/__tests__/attempt.test.js +0 -275
- package/dist/commands/hook/__tests__/attempt.test.js.map +0 -1
- package/dist/commands/hook/__tests__/create.test.js +0 -119
- package/dist/commands/hook/__tests__/create.test.js.map +0 -1
- package/dist/commands/hook/__tests__/delete.test.js +0 -233
- package/dist/commands/hook/__tests__/delete.test.js.map +0 -1
- package/dist/commands/hook/__tests__/list.test.js +0 -145
- package/dist/commands/hook/__tests__/list.test.js.map +0 -1
- package/dist/commands/hook/__tests__/logs.test.js +0 -798
- package/dist/commands/hook/__tests__/logs.test.js.map +0 -1
- package/dist/commands/manifest/__tests__/extract.test.js +0 -132
- package/dist/commands/manifest/__tests__/extract.test.js.map +0 -1
- package/dist/commands/mcp/__tests__/configure.test.js +0 -397
- package/dist/commands/mcp/__tests__/configure.test.js.map +0 -1
- package/dist/commands/media/__tests__/create-aspect.test.js +0 -173
- package/dist/commands/media/__tests__/create-aspect.test.js.map +0 -1
- package/dist/commands/media/__tests__/delete-aspect.test.js +0 -342
- package/dist/commands/media/__tests__/delete-aspect.test.js.map +0 -1
- package/dist/commands/media/__tests__/deploy-aspect.test.js +0 -619
- package/dist/commands/media/__tests__/deploy-aspect.test.js.map +0 -1
- package/dist/commands/media/__tests__/export.test.js +0 -697
- package/dist/commands/media/__tests__/export.test.js.map +0 -1
- package/dist/commands/media/__tests__/import.test.js +0 -347
- package/dist/commands/media/__tests__/import.test.js.map +0 -1
- package/dist/commands/openapi/__tests__/get.test.js +0 -149
- package/dist/commands/openapi/__tests__/get.test.js.map +0 -1
- package/dist/commands/openapi/__tests__/list.test.js +0 -113
- package/dist/commands/openapi/__tests__/list.test.js.map +0 -1
- package/dist/commands/projects/__tests__/list.test.js +0 -154
- package/dist/commands/projects/__tests__/list.test.js.map +0 -1
- package/dist/commands/schema/__tests__/delete.test.js +0 -454
- package/dist/commands/schema/__tests__/delete.test.js.map +0 -1
- package/dist/commands/schema/__tests__/deploy.test.js +0 -348
- package/dist/commands/schema/__tests__/deploy.test.js.map +0 -1
- package/dist/commands/schema/__tests__/extract.test.js +0 -121
- package/dist/commands/schema/__tests__/extract.test.js.map +0 -1
- package/dist/commands/schema/__tests__/list.test.js +0 -399
- package/dist/commands/schema/__tests__/list.test.js.map +0 -1
- package/dist/commands/schema/__tests__/validate.test.js +0 -121
- package/dist/commands/schema/__tests__/validate.test.js.map +0 -1
- package/dist/commands/telemetry/__tests__/disable.test.js +0 -147
- package/dist/commands/telemetry/__tests__/disable.test.js.map +0 -1
- package/dist/commands/telemetry/__tests__/enable.test.js +0 -133
- package/dist/commands/telemetry/__tests__/enable.test.js.map +0 -1
- package/dist/commands/telemetry/__tests__/status.test.js +0 -155
- package/dist/commands/telemetry/__tests__/status.test.js.map +0 -1
- package/dist/commands/tokens/__tests__/add.test.js +0 -435
- package/dist/commands/tokens/__tests__/add.test.js.map +0 -1
- package/dist/commands/tokens/__tests__/delete.test.js +0 -405
- package/dist/commands/tokens/__tests__/delete.test.js.map +0 -1
- package/dist/commands/tokens/__tests__/list.test.js +0 -395
- package/dist/commands/tokens/__tests__/list.test.js.map +0 -1
- package/dist/commands/users/__tests__/invite.test.js +0 -362
- package/dist/commands/users/__tests__/invite.test.js.map +0 -1
- package/dist/commands/users/__tests__/list.test.js +0 -407
- package/dist/commands/users/__tests__/list.test.js.map +0 -1
- package/dist/hooks/prerun/__tests__/setupTelemetry.test.js +0 -77
- package/dist/hooks/prerun/__tests__/setupTelemetry.test.js.map +0 -1
- package/dist/services/__tests__/datasetAliases.test.js +0 -131
- package/dist/services/__tests__/datasetAliases.test.js.map +0 -1
- package/dist/services/__tests__/datasets.test.js +0 -436
- package/dist/services/__tests__/datasets.test.js.map +0 -1
- package/dist/services/__tests__/graphql.test.js +0 -43
- package/dist/services/__tests__/graphql.test.js.map +0 -1
- package/dist/services/__tests__/mediaLibraries.test.js +0 -88
- package/dist/services/__tests__/mediaLibraries.test.js.map +0 -1
- package/dist/services/__tests__/projects.test.js +0 -41
- package/dist/services/__tests__/projects.test.js.map +0 -1
- package/dist/services/__tests__/userApplications.test.js +0 -113
- package/dist/services/__tests__/userApplications.test.js.map +0 -1
- package/dist/util/__tests__/appId.test.js +0 -31
- package/dist/util/__tests__/appId.test.js.map +0 -1
- package/dist/util/__tests__/cliClient.test.js +0 -184
- package/dist/util/__tests__/cliClient.test.js.map +0 -1
- package/dist/util/__tests__/compareDependencyVersions.test.js +0 -426
- package/dist/util/__tests__/compareDependencyVersions.test.js.map +0 -1
- package/dist/util/__tests__/extractDocumentsFromNdjsonOrTarball.test.js +0 -74
- package/dist/util/__tests__/extractDocumentsFromNdjsonOrTarball.test.js.map +0 -1
- package/dist/util/__tests__/findNdjsonEntry.test.js +0 -54
- package/dist/util/__tests__/findNdjsonEntry.test.js.map +0 -1
- package/dist/util/__tests__/getCliVersion.test.js +0 -28
- package/dist/util/__tests__/getCliVersion.test.js.map +0 -1
- package/dist/util/__tests__/getLocalPackageVersion.test.js +0 -84
- package/dist/util/__tests__/getLocalPackageVersion.test.js.map +0 -1
- package/dist/util/__tests__/getWorkspace.test.js +0 -37
- package/dist/util/__tests__/getWorkspace.test.js.map +0 -1
- package/dist/util/__tests__/readPackageJson.test.js +0 -69
- package/dist/util/__tests__/readPackageJson.test.js.map +0 -1
- package/dist/util/__tests__/warnAboutMissingAppId.test.js +0 -28
- package/dist/util/__tests__/warnAboutMissingAppId.test.js.map +0 -1
- package/dist/util/packageManager/__tests__/installPackages.test.js +0 -388
- package/dist/util/packageManager/__tests__/installPackages.test.js.map +0 -1
- package/dist/util/validation/ __tests__/validateDocuments.test.js +0 -274
- package/dist/util/validation/ __tests__/validateDocuments.test.js.map +0 -1
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Output } from '@sanity/cli-core';
|
|
2
|
+
/**
|
|
3
|
+
* Options for creating a dataset
|
|
4
|
+
*/
|
|
5
|
+
export interface CreateDatasetOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Name of the dataset to create
|
|
8
|
+
*/
|
|
9
|
+
datasetName: string;
|
|
10
|
+
/**
|
|
11
|
+
* Output instance for logging
|
|
12
|
+
*/
|
|
13
|
+
output: Output;
|
|
14
|
+
/**
|
|
15
|
+
* Array of project features to determine capabilities
|
|
16
|
+
* Used to check if private datasets are available
|
|
17
|
+
*/
|
|
18
|
+
projectFeatures: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Project ID where the dataset will be created
|
|
21
|
+
*/
|
|
22
|
+
projectId: string;
|
|
23
|
+
/**
|
|
24
|
+
* Whether to force disable private dataset creation
|
|
25
|
+
* Used when default config is selected (which forces public datasets)
|
|
26
|
+
*/
|
|
27
|
+
forcePublic?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Whether to run in unattended mode (no prompts)
|
|
30
|
+
*/
|
|
31
|
+
isUnattended?: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Requested visibility mode from flags/options
|
|
34
|
+
*/
|
|
35
|
+
visibility?: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new dataset with the appropriate ACL mode.
|
|
39
|
+
*
|
|
40
|
+
* This action handles the business logic for:
|
|
41
|
+
* - Determining the appropriate ACL mode based on project capabilities
|
|
42
|
+
* - Creating the dataset via the service layer
|
|
43
|
+
* - Handling errors and providing user feedback
|
|
44
|
+
*
|
|
45
|
+
* @param options - Configuration options
|
|
46
|
+
* @returns Promise resolving when dataset is created
|
|
47
|
+
* @throws Error if dataset creation fails
|
|
48
|
+
*/
|
|
49
|
+
export declare function createDataset(options: CreateDatasetOptions): Promise<void>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { subdebug } from '@sanity/cli-core';
|
|
2
|
+
import { spinner } from '@sanity/cli-core/ux';
|
|
3
|
+
import { createDataset as createDatasetService } from '../../services/datasets.js';
|
|
4
|
+
import { determineDatasetAclMode } from './determineDatasetAclMode.js';
|
|
5
|
+
const debug = subdebug('dataset:create');
|
|
6
|
+
/**
|
|
7
|
+
* Creates a new dataset with the appropriate ACL mode.
|
|
8
|
+
*
|
|
9
|
+
* This action handles the business logic for:
|
|
10
|
+
* - Determining the appropriate ACL mode based on project capabilities
|
|
11
|
+
* - Creating the dataset via the service layer
|
|
12
|
+
* - Handling errors and providing user feedback
|
|
13
|
+
*
|
|
14
|
+
* @param options - Configuration options
|
|
15
|
+
* @returns Promise resolving when dataset is created
|
|
16
|
+
* @throws Error if dataset creation fails
|
|
17
|
+
*/ export async function createDataset(options) {
|
|
18
|
+
const { datasetName, forcePublic = false, isUnattended = false, output, projectFeatures, projectId, visibility } = options;
|
|
19
|
+
const canCreatePrivate = projectFeatures.includes('privateDataset') && !forcePublic;
|
|
20
|
+
// Determine the appropriate ACL mode
|
|
21
|
+
const aclMode = await determineDatasetAclMode({
|
|
22
|
+
canCreatePrivate,
|
|
23
|
+
isUnattended,
|
|
24
|
+
output,
|
|
25
|
+
visibility
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
const spin = spinner('Creating dataset').start();
|
|
29
|
+
await createDatasetService({
|
|
30
|
+
aclMode,
|
|
31
|
+
datasetName,
|
|
32
|
+
projectId
|
|
33
|
+
});
|
|
34
|
+
spin.succeed();
|
|
35
|
+
output.log(`Dataset created successfully`);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
38
|
+
debug('Error creating dataset', {
|
|
39
|
+
datasetName,
|
|
40
|
+
error
|
|
41
|
+
});
|
|
42
|
+
output.error(`Dataset creation failed: ${message}`, {
|
|
43
|
+
exit: 1
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=create.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dataset/create.ts"],"sourcesContent":["import {type Output, subdebug} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {type DatasetAclMode} from '@sanity/client'\n\nimport {createDataset as createDatasetService} from '../../services/datasets.js'\nimport {determineDatasetAclMode} from './determineDatasetAclMode.js'\n\nconst debug = subdebug('dataset:create')\n\n/**\n * Options for creating a dataset\n */\nexport interface CreateDatasetOptions {\n /**\n * Name of the dataset to create\n */\n datasetName: string\n\n /**\n * Output instance for logging\n */\n output: Output\n\n /**\n * Array of project features to determine capabilities\n * Used to check if private datasets are available\n */\n projectFeatures: string[]\n\n /**\n * Project ID where the dataset will be created\n */\n projectId: string\n\n /**\n * Whether to force disable private dataset creation\n * Used when default config is selected (which forces public datasets)\n */\n forcePublic?: boolean\n\n /**\n * Whether to run in unattended mode (no prompts)\n */\n isUnattended?: boolean\n\n /**\n * Requested visibility mode from flags/options\n */\n visibility?: string\n}\n\n/**\n * Creates a new dataset with the appropriate ACL mode.\n *\n * This action handles the business logic for:\n * - Determining the appropriate ACL mode based on project capabilities\n * - Creating the dataset via the service layer\n * - Handling errors and providing user feedback\n *\n * @param options - Configuration options\n * @returns Promise resolving when dataset is created\n * @throws Error if dataset creation fails\n */\nexport async function createDataset(options: CreateDatasetOptions): Promise<void> {\n const {\n datasetName,\n forcePublic = false,\n isUnattended = false,\n output,\n projectFeatures,\n projectId,\n visibility,\n } = options\n\n const canCreatePrivate = projectFeatures.includes('privateDataset') && !forcePublic\n\n // Determine the appropriate ACL mode\n const aclMode: DatasetAclMode = await determineDatasetAclMode({\n canCreatePrivate,\n isUnattended,\n output,\n visibility,\n })\n\n try {\n const spin = spinner('Creating dataset').start()\n await createDatasetService({\n aclMode,\n datasetName,\n projectId,\n })\n spin.succeed()\n output.log(`Dataset created successfully`)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n debug('Error creating dataset', {datasetName, error})\n output.error(`Dataset creation failed: ${message}`, {exit: 1})\n }\n}\n"],"names":["subdebug","spinner","createDataset","createDatasetService","determineDatasetAclMode","debug","options","datasetName","forcePublic","isUnattended","output","projectFeatures","projectId","visibility","canCreatePrivate","includes","aclMode","spin","start","succeed","log","error","message","Error","String","exit"],"mappings":"AAAA,SAAqBA,QAAQ,QAAO,mBAAkB;AACtD,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,iBAAiBC,oBAAoB,QAAO,6BAA4B;AAChF,SAAQC,uBAAuB,QAAO,+BAA8B;AAEpE,MAAMC,QAAQL,SAAS;AA4CvB;;;;;;;;;;;CAWC,GACD,OAAO,eAAeE,cAAcI,OAA6B;IAC/D,MAAM,EACJC,WAAW,EACXC,cAAc,KAAK,EACnBC,eAAe,KAAK,EACpBC,MAAM,EACNC,eAAe,EACfC,SAAS,EACTC,UAAU,EACX,GAAGP;IAEJ,MAAMQ,mBAAmBH,gBAAgBI,QAAQ,CAAC,qBAAqB,CAACP;IAExE,qCAAqC;IACrC,MAAMQ,UAA0B,MAAMZ,wBAAwB;QAC5DU;QACAL;QACAC;QACAG;IACF;IAEA,IAAI;QACF,MAAMI,OAAOhB,QAAQ,oBAAoBiB,KAAK;QAC9C,MAAMf,qBAAqB;YACzBa;YACAT;YACAK;QACF;QACAK,KAAKE,OAAO;QACZT,OAAOU,GAAG,CAAC,CAAC,4BAA4B,CAAC;IAC3C,EAAE,OAAOC,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGE,OAAOH;QAChEhB,MAAM,0BAA0B;YAACE;YAAac;QAAK;QACnDX,OAAOW,KAAK,CAAC,CAAC,yBAAyB,EAAEC,SAAS,EAAE;YAACG,MAAM;QAAC;IAC9D;AACF"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type Output } from '@sanity/cli-core';
|
|
2
|
+
import { type DatasetAclMode } from '@sanity/client';
|
|
3
|
+
/**
|
|
4
|
+
* Options for determining the ACL mode for a dataset
|
|
5
|
+
*/
|
|
6
|
+
export interface DetermineDatasetAclModeOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Whether the project has the capability to create private datasets
|
|
9
|
+
*/
|
|
10
|
+
canCreatePrivate: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Output instance for logging warnings
|
|
13
|
+
*/
|
|
14
|
+
output: Output;
|
|
15
|
+
/**
|
|
16
|
+
* Whether to run in unattended mode (no prompts)
|
|
17
|
+
*/
|
|
18
|
+
isUnattended?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Requested visibility mode from flags/options
|
|
21
|
+
*/
|
|
22
|
+
visibility?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Determines the appropriate ACL mode for a dataset based on project capabilities
|
|
26
|
+
* and user preferences.
|
|
27
|
+
*
|
|
28
|
+
* This action handles the business logic for:
|
|
29
|
+
* - Validating requested visibility against project capabilities
|
|
30
|
+
* - Falling back to public when private is not available
|
|
31
|
+
* - Prompting user when necessary
|
|
32
|
+
* - Warning user about limitations
|
|
33
|
+
*
|
|
34
|
+
* @param options - Configuration options
|
|
35
|
+
* @returns Promise resolving to the determined ACL mode
|
|
36
|
+
*/
|
|
37
|
+
export declare function determineDatasetAclMode(options: DetermineDatasetAclModeOptions): Promise<DatasetAclMode>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { promptForDatasetAclMode } from '../../prompts/promptForDatasetAclMode.js';
|
|
2
|
+
/**
|
|
3
|
+
* Determines the appropriate ACL mode for a dataset based on project capabilities
|
|
4
|
+
* and user preferences.
|
|
5
|
+
*
|
|
6
|
+
* This action handles the business logic for:
|
|
7
|
+
* - Validating requested visibility against project capabilities
|
|
8
|
+
* - Falling back to public when private is not available
|
|
9
|
+
* - Prompting user when necessary
|
|
10
|
+
* - Warning user about limitations
|
|
11
|
+
*
|
|
12
|
+
* @param options - Configuration options
|
|
13
|
+
* @returns Promise resolving to the determined ACL mode
|
|
14
|
+
*/ export async function determineDatasetAclMode(options) {
|
|
15
|
+
const { canCreatePrivate, isUnattended = false, output, visibility } = options;
|
|
16
|
+
// Handle explicit custom/public requests
|
|
17
|
+
if (visibility === 'custom' || visibility === 'public') {
|
|
18
|
+
return visibility;
|
|
19
|
+
}
|
|
20
|
+
// Handle private visibility request
|
|
21
|
+
if (visibility === 'private') {
|
|
22
|
+
if (canCreatePrivate) {
|
|
23
|
+
return 'private';
|
|
24
|
+
}
|
|
25
|
+
output.warn('Private datasets are not available for this project. Creating as public.');
|
|
26
|
+
return 'public';
|
|
27
|
+
}
|
|
28
|
+
// No explicit request - determine based on capabilities and mode
|
|
29
|
+
if (isUnattended || !canCreatePrivate) {
|
|
30
|
+
return 'public';
|
|
31
|
+
}
|
|
32
|
+
// Interactive mode with private capability - prompt user
|
|
33
|
+
return promptForDatasetAclMode(output);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=determineDatasetAclMode.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dataset/determineDatasetAclMode.ts"],"sourcesContent":["import {type Output} from '@sanity/cli-core'\nimport {type DatasetAclMode} from '@sanity/client'\n\nimport {promptForDatasetAclMode} from '../../prompts/promptForDatasetAclMode.js'\n\n/**\n * Options for determining the ACL mode for a dataset\n */\nexport interface DetermineDatasetAclModeOptions {\n /**\n * Whether the project has the capability to create private datasets\n */\n canCreatePrivate: boolean\n /**\n * Output instance for logging warnings\n */\n output: Output\n\n /**\n * Whether to run in unattended mode (no prompts)\n */\n isUnattended?: boolean\n /**\n * Requested visibility mode from flags/options\n */\n visibility?: string\n}\n\n/**\n * Determines the appropriate ACL mode for a dataset based on project capabilities\n * and user preferences.\n *\n * This action handles the business logic for:\n * - Validating requested visibility against project capabilities\n * - Falling back to public when private is not available\n * - Prompting user when necessary\n * - Warning user about limitations\n *\n * @param options - Configuration options\n * @returns Promise resolving to the determined ACL mode\n */\nexport async function determineDatasetAclMode(\n options: DetermineDatasetAclModeOptions,\n): Promise<DatasetAclMode> {\n const {canCreatePrivate, isUnattended = false, output, visibility} = options\n\n // Handle explicit custom/public requests\n if (visibility === 'custom' || visibility === 'public') {\n return visibility\n }\n\n // Handle private visibility request\n if (visibility === 'private') {\n if (canCreatePrivate) {\n return 'private'\n }\n\n output.warn('Private datasets are not available for this project. Creating as public.')\n\n return 'public'\n }\n\n // No explicit request - determine based on capabilities and mode\n if (isUnattended || !canCreatePrivate) {\n return 'public'\n }\n\n // Interactive mode with private capability - prompt user\n return promptForDatasetAclMode(output)\n}\n"],"names":["promptForDatasetAclMode","determineDatasetAclMode","options","canCreatePrivate","isUnattended","output","visibility","warn"],"mappings":"AAGA,SAAQA,uBAAuB,QAAO,2CAA0C;AAyBhF;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,wBACpBC,OAAuC;IAEvC,MAAM,EAACC,gBAAgB,EAAEC,eAAe,KAAK,EAAEC,MAAM,EAAEC,UAAU,EAAC,GAAGJ;IAErE,yCAAyC;IACzC,IAAII,eAAe,YAAYA,eAAe,UAAU;QACtD,OAAOA;IACT;IAEA,oCAAoC;IACpC,IAAIA,eAAe,WAAW;QAC5B,IAAIH,kBAAkB;YACpB,OAAO;QACT;QAEAE,OAAOE,IAAI,CAAC;QAEZ,OAAO;IACT;IAEA,iEAAiE;IACjE,IAAIH,gBAAgB,CAACD,kBAAkB;QACrC,OAAO;IACT;IAEA,yDAAyD;IACzD,OAAOH,wBAAwBK;AACjC"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { getCliToken,
|
|
1
|
+
import { getCliToken, getUserConfig } from '@sanity/cli-core';
|
|
2
|
+
import { getProjectById } from '../../services/projects.js';
|
|
3
|
+
import { getCliUser, getProjectUser } from '../../services/user.js';
|
|
2
4
|
import { findSanityModulesVersions } from '../versions/findSanityModulesVersions.js';
|
|
3
5
|
export async function gatherDebugInfo(options) {
|
|
4
|
-
const { cliConfig,
|
|
6
|
+
const { cliConfig, includeSecrets, projectRoot } = options;
|
|
5
7
|
// Gather all info in parallel where possible
|
|
6
8
|
const [auth, globalConfig, projectConfigResult, versions] = await Promise.all([
|
|
7
9
|
gatherAuthInfo(includeSecrets),
|
|
@@ -10,8 +12,8 @@ export async function gatherDebugInfo(options) {
|
|
|
10
12
|
gatherVersionsInfo(projectRoot)
|
|
11
13
|
]);
|
|
12
14
|
// Gather user and project info that depend on auth
|
|
13
|
-
const user = await gatherUserInfo(
|
|
14
|
-
const project = await gatherProjectInfo(
|
|
15
|
+
const user = await gatherUserInfo(projectConfigResult, auth.hasToken);
|
|
16
|
+
const project = await gatherProjectInfo(projectConfigResult, auth.hasToken, user);
|
|
15
17
|
return {
|
|
16
18
|
auth,
|
|
17
19
|
globalConfig,
|
|
@@ -30,19 +32,8 @@ async function gatherAuthInfo(includeSecrets) {
|
|
|
30
32
|
userType: 'normal'
|
|
31
33
|
};
|
|
32
34
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
const [authToken, telemetryConsent] = await Promise.all([
|
|
36
|
-
getCliUserConfig('authToken'),
|
|
37
|
-
getCliUserConfig('telemetryConsent')
|
|
38
|
-
]);
|
|
39
|
-
return {
|
|
40
|
-
authToken,
|
|
41
|
-
telemetryConsent
|
|
42
|
-
};
|
|
43
|
-
} catch {
|
|
44
|
-
return {};
|
|
45
|
-
}
|
|
35
|
+
function gatherGlobalConfig() {
|
|
36
|
+
return getUserConfig().all;
|
|
46
37
|
}
|
|
47
38
|
async function gatherProjectConfig(cliConfig) {
|
|
48
39
|
try {
|
|
@@ -64,12 +55,15 @@ async function gatherVersionsInfo(projectRoot) {
|
|
|
64
55
|
return [];
|
|
65
56
|
}
|
|
66
57
|
}
|
|
67
|
-
async function gatherUserInfo(
|
|
58
|
+
async function gatherUserInfo(projectConfig, hasToken) {
|
|
68
59
|
if (!hasToken) {
|
|
69
60
|
return new Error('Not logged in');
|
|
70
61
|
}
|
|
71
62
|
try {
|
|
72
|
-
|
|
63
|
+
/**
|
|
64
|
+
* If the project config has a project ID, get the user for the project
|
|
65
|
+
* Otherwise, get the user for the global client
|
|
66
|
+
*/ const userInfo = projectConfig instanceof Error || !projectConfig.api?.projectId ? await getCliUser() : await getProjectUser(projectConfig.api.projectId);
|
|
73
67
|
return {
|
|
74
68
|
email: userInfo.email,
|
|
75
69
|
id: userInfo.id,
|
|
@@ -79,7 +73,7 @@ async function gatherUserInfo(client, hasToken) {
|
|
|
79
73
|
return error instanceof Error ? error : new Error('Failed to fetch user info');
|
|
80
74
|
}
|
|
81
75
|
}
|
|
82
|
-
async function gatherProjectInfo(
|
|
76
|
+
async function gatherProjectInfo(projectConfig, hasToken, user) {
|
|
83
77
|
if (!hasToken || projectConfig instanceof Error) {
|
|
84
78
|
return null;
|
|
85
79
|
}
|
|
@@ -88,7 +82,7 @@ async function gatherProjectInfo(client, projectConfig, hasToken, user) {
|
|
|
88
82
|
return null;
|
|
89
83
|
}
|
|
90
84
|
try {
|
|
91
|
-
const projectInfo = await
|
|
85
|
+
const projectInfo = await getProjectById(projectId);
|
|
92
86
|
if (!projectInfo) {
|
|
93
87
|
return new Error(`Project specified in configuration (${projectId}) does not exist in API`);
|
|
94
88
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/debug/gatherDebugInfo.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/debug/gatherDebugInfo.ts"],"sourcesContent":["import {type CliConfig, getCliToken, getUserConfig, type ProjectRootResult} from '@sanity/cli-core'\n\nimport {getProjectById} from '../../services/projects.js'\nimport {getCliUser, getProjectUser} from '../../services/user.js'\nimport {findSanityModulesVersions} from '../versions/findSanityModulesVersions.js'\nimport {type ModuleVersionResult} from '../versions/types.js'\nimport {\n type AuthInfo,\n type DebugInfo,\n type DebugInfoOptions,\n type ProjectInfo,\n type UserInfo,\n} from './types.js'\n\nexport async function gatherDebugInfo(options: DebugInfoOptions): Promise<DebugInfo> {\n const {cliConfig, includeSecrets, projectRoot} = options\n\n // Gather all info in parallel where possible\n const [auth, globalConfig, projectConfigResult, versions] = await Promise.all([\n gatherAuthInfo(includeSecrets),\n gatherGlobalConfig(),\n gatherProjectConfig(cliConfig),\n gatherVersionsInfo(projectRoot),\n ])\n\n // Gather user and project info that depend on auth\n const user = await gatherUserInfo(projectConfigResult, auth.hasToken)\n const project = await gatherProjectInfo(projectConfigResult, auth.hasToken, user)\n\n return {\n auth,\n globalConfig,\n project,\n projectConfig: projectConfigResult,\n user,\n versions,\n }\n}\n\nasync function gatherAuthInfo(includeSecrets: boolean): Promise<AuthInfo> {\n const token = await getCliToken()\n const hasToken = Boolean(token)\n\n return {\n authToken: includeSecrets && token ? token : '<redacted>',\n hasToken,\n userType: 'normal',\n }\n}\n\nfunction gatherGlobalConfig(): Record<string, unknown> {\n return getUserConfig().all\n}\n\nasync function gatherProjectConfig(cliConfig: CliConfig): Promise<CliConfig | Error> {\n try {\n const config = cliConfig\n\n if (!config.api?.projectId) {\n return new Error('Missing required \"api.projectId\" key')\n }\n\n return config\n } catch (error) {\n return error instanceof Error ? error : new Error('Failed to load project config')\n }\n}\n\nasync function gatherVersionsInfo(projectRoot: ProjectRootResult): Promise<ModuleVersionResult[]> {\n try {\n return await findSanityModulesVersions({cwd: projectRoot.directory})\n } catch {\n return []\n }\n}\n\nasync function gatherUserInfo(\n projectConfig: CliConfig | Error,\n hasToken: boolean,\n): Promise<Error | UserInfo | null> {\n if (!hasToken) {\n return new Error('Not logged in')\n }\n\n try {\n /**\n * If the project config has a project ID, get the user for the project\n * Otherwise, get the user for the global client\n */\n const userInfo =\n projectConfig instanceof Error || !projectConfig.api?.projectId\n ? await getCliUser()\n : await getProjectUser(projectConfig.api.projectId)\n\n return {\n email: userInfo.email,\n id: userInfo.id,\n name: userInfo.name,\n }\n } catch (error) {\n return error instanceof Error ? error : new Error('Failed to fetch user info')\n }\n}\n\nasync function gatherProjectInfo(\n projectConfig: CliConfig | Error,\n hasToken: boolean,\n user: Error | UserInfo | null,\n): Promise<Error | ProjectInfo | null> {\n if (!hasToken || projectConfig instanceof Error) {\n return null\n }\n\n const projectId = projectConfig.api?.projectId\n if (!projectId) {\n return null\n }\n\n try {\n const projectInfo = await getProjectById(projectId)\n\n if (!projectInfo) {\n return new Error(`Project specified in configuration (${projectId}) does not exist in API`)\n }\n\n const userId = user instanceof Error || !user ? null : user.id\n const member = (projectInfo.members || []).find((member) => member.id === userId)\n\n return {\n displayName: projectInfo.displayName,\n id: projectId,\n // @ts-expect-error - Incorrect type definition in @sanity/client\n userRoles: member && member.roles ? member.roles.map((role) => role.name) : ['<none>'],\n }\n } catch (error) {\n return error instanceof Error ? error : new Error('Failed to fetch project info')\n }\n}\n"],"names":["getCliToken","getUserConfig","getProjectById","getCliUser","getProjectUser","findSanityModulesVersions","gatherDebugInfo","options","cliConfig","includeSecrets","projectRoot","auth","globalConfig","projectConfigResult","versions","Promise","all","gatherAuthInfo","gatherGlobalConfig","gatherProjectConfig","gatherVersionsInfo","user","gatherUserInfo","hasToken","project","gatherProjectInfo","projectConfig","token","Boolean","authToken","userType","config","api","projectId","Error","error","cwd","directory","userInfo","email","id","name","projectInfo","userId","member","members","find","displayName","userRoles","roles","map","role"],"mappings":"AAAA,SAAwBA,WAAW,EAAEC,aAAa,QAA+B,mBAAkB;AAEnG,SAAQC,cAAc,QAAO,6BAA4B;AACzD,SAAQC,UAAU,EAAEC,cAAc,QAAO,yBAAwB;AACjE,SAAQC,yBAAyB,QAAO,2CAA0C;AAUlF,OAAO,eAAeC,gBAAgBC,OAAyB;IAC7D,MAAM,EAACC,SAAS,EAAEC,cAAc,EAAEC,WAAW,EAAC,GAAGH;IAEjD,6CAA6C;IAC7C,MAAM,CAACI,MAAMC,cAAcC,qBAAqBC,SAAS,GAAG,MAAMC,QAAQC,GAAG,CAAC;QAC5EC,eAAeR;QACfS;QACAC,oBAAoBX;QACpBY,mBAAmBV;KACpB;IAED,mDAAmD;IACnD,MAAMW,OAAO,MAAMC,eAAeT,qBAAqBF,KAAKY,QAAQ;IACpE,MAAMC,UAAU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AyBQ,OAAO;QAC/C,OAAO;IACT;IAEA,MAAMD,YAAYP,cAAcM,GAAG,EAAEC;IACrC,IAAI,CAACA,WAAW;QACd,OAAO;IACT;IAEA,IAAI;QACF,MAAMS,cAAc,MAAMxC,eAAe+B;QAEzC,IAAI,CAACS,aAAa;YAChB,OAAO,IAAIR,MAAM,CAAC,oCAAoC,EAAED,UAAU,uBAAuB,CAAC;QAC5F;QAEA,MAAMU,SAAStB,gBAAgBa,SAAS,CAACb,OAAO,OAAOA,KAAKmB,EAAE;QAC9D,MAAMI,SAAS,AAACF,CAAAA,YAAYG,OAAO,IAAI,EAAE,AAAD,EAAGC,IAAI,CAAC,CAACF,SAAWA,OAAOJ,EAAE,KAAKG;QAE1E,OAAO;YACLI,aAAaL,YAAYK,WAAW;YACpCP,IAAIP;YACJ,iEAAiE;YACjEe,WAAWJ,UAAUA,OAAOK,KAAK,GAAGL,OAAOK,KAAK,CAACC,GAAG,CAAC,CAACC,OAASA,KAAKV,IAAI,IAAI;gBAAC;aAAS;QACxF;IACF,EAAE,OAAON,OAAO;QACd,OAAOA,iBAAiBD,QAAQC,QAAQ,IAAID,MAAM;IACpD;AACF"}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { type CliConfig, type ProjectRootResult } from '@sanity/cli-core';
|
|
2
|
-
import { type SanityClient } from '@sanity/client';
|
|
3
2
|
import { type ModuleVersionResult } from '../versions/types.js';
|
|
4
3
|
export interface DebugInfoOptions {
|
|
5
4
|
cliConfig: CliConfig;
|
|
6
|
-
client: SanityClient;
|
|
7
5
|
includeSecrets: boolean;
|
|
8
6
|
projectRoot: ProjectRootResult;
|
|
9
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/debug/types.ts"],"sourcesContent":["import {type CliConfig, type ProjectRootResult} from '@sanity/cli-core'\
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/debug/types.ts"],"sourcesContent":["import {type CliConfig, type ProjectRootResult} from '@sanity/cli-core'\n\nimport {type ModuleVersionResult} from '../versions/types.js'\n\nexport interface DebugInfoOptions {\n cliConfig: CliConfig\n includeSecrets: boolean\n projectRoot: ProjectRootResult\n}\n\nexport interface UserInfo {\n email: string\n id: string\n name: string\n}\n\nexport interface ProjectInfo {\n displayName: string\n id: string\n userRoles: string[]\n}\n\nexport interface AuthInfo {\n authToken: string\n hasToken: boolean\n userType: string\n}\n\nexport interface DebugInfo {\n auth: AuthInfo\n globalConfig: Record<string, unknown>\n project: Error | ProjectInfo | null\n projectConfig: CliConfig | Error\n user: Error | UserInfo | null\n versions: ModuleVersionResult[]\n}\n"],"names":[],"mappings":"AA4BA,WAOC"}
|
|
@@ -10,6 +10,7 @@ import { readModuleVersion } from '../../util/readModuleVersion.js';
|
|
|
10
10
|
import { warnAboutMissingAppId } from '../../util/warnAboutMissingAppId.js';
|
|
11
11
|
import { buildApp } from '../build/buildApp.js';
|
|
12
12
|
import { shouldAutoUpdate } from '../build/shouldAutoUpdate.js';
|
|
13
|
+
import { extractAppManifest } from '../manifest/extractAppManifest.js';
|
|
13
14
|
import { checkDir } from './checkDir.js';
|
|
14
15
|
import { createUserApplicationForApp } from './createUserApplicationForApp.js';
|
|
15
16
|
import { deployDebug } from './deployDebug.js';
|
|
@@ -95,11 +96,23 @@ import { findUserApplicationForApp } from './findUserApplicationForApp.js';
|
|
|
95
96
|
base
|
|
96
97
|
]
|
|
97
98
|
}).pipe(createGzip());
|
|
99
|
+
let manifest;
|
|
100
|
+
try {
|
|
101
|
+
manifest = await extractAppManifest({
|
|
102
|
+
flags,
|
|
103
|
+
workDir
|
|
104
|
+
});
|
|
105
|
+
} catch (err) {
|
|
106
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
107
|
+
deployDebug('Error extracting app manifest', err);
|
|
108
|
+
output.warn(`Error extracting app manifest: ${message}`);
|
|
109
|
+
}
|
|
98
110
|
spin = spinner('Deploying...').start();
|
|
99
111
|
await createDeployment({
|
|
100
112
|
applicationId: userApplication.id,
|
|
101
113
|
isApp: true,
|
|
102
114
|
isAutoUpdating,
|
|
115
|
+
manifest,
|
|
103
116
|
tarball,
|
|
104
117
|
version: installedSdkVersion
|
|
105
118
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/deployApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_ORGANIZATION_ID} from '../../util/errorMessages.js'\nimport {readModuleVersion} from '../../util/readModuleVersion.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildApp} from '../build/buildApp.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {checkDir} from './checkDir.js'\nimport {createUserApplicationForApp} from './createUserApplicationForApp.js'\nimport {deployDebug} from './deployDebug.js'\nimport {findUserApplicationForApp} from './findUserApplicationForApp.js'\nimport {type DeployAppOptions} from './types.js'\n\n/**\n * Deploy a Sanity application.\n *\n * @internal\n */\nexport async function deployApp(options: DeployAppOptions) {\n const {cliConfig, exit, flags, output, sourceDir, workDir} = options\n\n const organizationId = cliConfig.app?.organizationId\n const appId = getAppId(cliConfig)\n const isAutoUpdating = shouldAutoUpdate({cliConfig, flags, output})\n const installedSdkVersion = await readModuleVersion(sourceDir, '@sanity/sdk-react')\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n if (!organizationId) {\n output.error(NO_ORGANIZATION_ID, {exit: 1})\n return\n }\n\n let spin = spinner('Verifying local content...')\n\n try {\n let userApplication = await findUserApplicationForApp({\n cliConfig,\n organizationId,\n output,\n })\n\n deployDebug(`User application found`, userApplication)\n\n if (!userApplication) {\n deployDebug(`No user application found. Creating a new one`)\n\n userApplication = await createUserApplicationForApp(organizationId)\n deployDebug(`User application created`, userApplication)\n }\n\n // Warn about missing app ID if auto updates are enabled\n if (isAutoUpdating && !appId) {\n warnAboutMissingAppId({appType: 'app', output})\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n deployDebug(`Building app`)\n await buildApp({\n autoUpdatesEnabled: isAutoUpdating,\n cliConfig,\n exit,\n flags,\n outDir: sourceDir,\n output,\n workDir,\n })\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spin = spin.start()\n try {\n await checkDir(sourceDir)\n spin.succeed()\n } catch (err) {\n spin.fail()\n deployDebug('Error checking directory', err)\n output.error('Error checking directory', {exit: 1})\n return\n }\n\n // Create a tarball of the given directory\n const parentDir = dirname(sourceDir)\n const base = basename(sourceDir)\n const tarball = pack(parentDir, {entries: [base]}).pipe(createGzip())\n\n spin = spinner('Deploying...').start()\n await createDeployment({\n applicationId: userApplication.id,\n isApp: true,\n isAutoUpdating,\n tarball,\n version: installedSdkVersion,\n })\n\n spin.succeed()\n\n // And let the user know we're done\n output.log(`\\n🚀 ${chalk.bold('Success!')} Application deployed`)\n\n if (!appId) {\n output.log(`\\n════ ${chalk.bold('Next step:')} ════`)\n output.log(\n chalk.bold('\\nAdd the deployment.appId to your sanity.cli.js or sanity.cli.ts file:'),\n )\n output.log(`\n${chalk.dim(`app: {\n // your application config here…\n}`)},\n${chalk.bold.green(`deployment: {\n appId: '${userApplication.id}',\n}\\n`)}`)\n }\n } catch (error) {\n spin.clear()\n // Don't throw generic error if user cancels\n if (error.name === 'ExitPromptError') {\n output.error('Deployment cancelled by user', {exit: 1})\n return\n }\n // If the error is a CLIError, we can just output the message & error options (if any), while ensuring we exit\n if (error instanceof CLIError) {\n const {message, ...errorOptions} = error\n output.error(message, {...errorOptions, exit: 1})\n return\n }\n\n deployDebug('Error deploying application', error)\n output.error('Error deploying application', {exit: 1})\n }\n}\n"],"names":["basename","dirname","createGzip","CLIError","chalk","spinner","pack","createDeployment","getAppId","NO_ORGANIZATION_ID","readModuleVersion","warnAboutMissingAppId","buildApp","shouldAutoUpdate","checkDir","createUserApplicationForApp","deployDebug","findUserApplicationForApp","deployApp","options","cliConfig","exit","flags","output","sourceDir","workDir","organizationId","app","appId","isAutoUpdating","installedSdkVersion","error","spin","userApplication","appType","shouldBuild","build","autoUpdatesEnabled","outDir","start","succeed","err","fail","parentDir","base","tarball","entries","pipe","applicationId","id","isApp","version","log","bold","dim","green","clear","name","
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/deployApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {chalk, spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_ORGANIZATION_ID} from '../../util/errorMessages.js'\nimport {readModuleVersion} from '../../util/readModuleVersion.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildApp} from '../build/buildApp.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {extractAppManifest} from '../manifest/extractAppManifest.js'\nimport {type AppManifest} from '../manifest/types.js'\nimport {checkDir} from './checkDir.js'\nimport {createUserApplicationForApp} from './createUserApplicationForApp.js'\nimport {deployDebug} from './deployDebug.js'\nimport {findUserApplicationForApp} from './findUserApplicationForApp.js'\nimport {type DeployAppOptions} from './types.js'\n\n/**\n * Deploy a Sanity application.\n *\n * @internal\n */\nexport async function deployApp(options: DeployAppOptions) {\n const {cliConfig, exit, flags, output, sourceDir, workDir} = options\n\n const organizationId = cliConfig.app?.organizationId\n const appId = getAppId(cliConfig)\n const isAutoUpdating = shouldAutoUpdate({cliConfig, flags, output})\n const installedSdkVersion = await readModuleVersion(sourceDir, '@sanity/sdk-react')\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n if (!organizationId) {\n output.error(NO_ORGANIZATION_ID, {exit: 1})\n return\n }\n\n let spin = spinner('Verifying local content...')\n\n try {\n let userApplication = await findUserApplicationForApp({\n cliConfig,\n organizationId,\n output,\n })\n\n deployDebug(`User application found`, userApplication)\n\n if (!userApplication) {\n deployDebug(`No user application found. Creating a new one`)\n\n userApplication = await createUserApplicationForApp(organizationId)\n deployDebug(`User application created`, userApplication)\n }\n\n // Warn about missing app ID if auto updates are enabled\n if (isAutoUpdating && !appId) {\n warnAboutMissingAppId({appType: 'app', output})\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n deployDebug(`Building app`)\n await buildApp({\n autoUpdatesEnabled: isAutoUpdating,\n cliConfig,\n exit,\n flags,\n outDir: sourceDir,\n output,\n workDir,\n })\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spin = spin.start()\n try {\n await checkDir(sourceDir)\n spin.succeed()\n } catch (err) {\n spin.fail()\n deployDebug('Error checking directory', err)\n output.error('Error checking directory', {exit: 1})\n return\n }\n\n // Create a tarball of the given directory\n const parentDir = dirname(sourceDir)\n const base = basename(sourceDir)\n const tarball = pack(parentDir, {entries: [base]}).pipe(createGzip())\n let manifest: AppManifest | undefined\n try {\n manifest = await extractAppManifest({flags, workDir})\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n deployDebug('Error extracting app manifest', err)\n output.warn(`Error extracting app manifest: ${message}`)\n }\n\n spin = spinner('Deploying...').start()\n await createDeployment({\n applicationId: userApplication.id,\n isApp: true,\n isAutoUpdating,\n manifest,\n tarball,\n version: installedSdkVersion,\n })\n\n spin.succeed()\n\n // And let the user know we're done\n output.log(`\\n🚀 ${chalk.bold('Success!')} Application deployed`)\n\n if (!appId) {\n output.log(`\\n════ ${chalk.bold('Next step:')} ════`)\n output.log(\n chalk.bold('\\nAdd the deployment.appId to your sanity.cli.js or sanity.cli.ts file:'),\n )\n output.log(`\n${chalk.dim(`app: {\n // your application config here…\n}`)},\n${chalk.bold.green(`deployment: {\n appId: '${userApplication.id}',\n}\\n`)}`)\n }\n } catch (error) {\n spin.clear()\n // Don't throw generic error if user cancels\n if (error.name === 'ExitPromptError') {\n output.error('Deployment cancelled by user', {exit: 1})\n return\n }\n // If the error is a CLIError, we can just output the message & error options (if any), while ensuring we exit\n if (error instanceof CLIError) {\n const {message, ...errorOptions} = error\n output.error(message, {...errorOptions, exit: 1})\n return\n }\n\n deployDebug('Error deploying application', error)\n output.error('Error deploying application', {exit: 1})\n }\n}\n"],"names":["basename","dirname","createGzip","CLIError","chalk","spinner","pack","createDeployment","getAppId","NO_ORGANIZATION_ID","readModuleVersion","warnAboutMissingAppId","buildApp","shouldAutoUpdate","extractAppManifest","checkDir","createUserApplicationForApp","deployDebug","findUserApplicationForApp","deployApp","options","cliConfig","exit","flags","output","sourceDir","workDir","organizationId","app","appId","isAutoUpdating","installedSdkVersion","error","spin","userApplication","appType","shouldBuild","build","autoUpdatesEnabled","outDir","start","succeed","err","fail","parentDir","base","tarball","entries","pipe","manifest","message","Error","String","warn","applicationId","id","isApp","version","log","bold","dim","green","clear","name","errorOptions"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,UAAU,QAAO,YAAW;AAEpC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,KAAK,EAAEC,OAAO,QAAO,sBAAqB;AAClD,SAAQC,IAAI,QAAO,SAAQ;AAE3B,SAAQC,gBAAgB,QAAO,qCAAoC;AACnE,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,kBAAkB,QAAO,8BAA6B;AAC9D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SAAQC,qBAAqB,QAAO,sCAAqC;AACzE,SAAQC,QAAQ,QAAO,uBAAsB;AAC7C,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,kBAAkB,QAAO,oCAAm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AE;AACJ,EAAExD,MAAMuD,IAAI,CAACE,KAAK,CAAC,CAAC;UACV,EAAE3B,gBAAgBqB,EAAE,CAAC;GAC5B,CAAC,GAAG;QACH;IACF,EAAE,OAAOvB,OAAO;QACdC,KAAK6B,KAAK;QACV,4CAA4C;QAC5C,IAAI9B,MAAM+B,IAAI,KAAK,mBAAmB;YACpCvC,OAAOQ,KAAK,CAAC,gCAAgC;gBAACV,MAAM;YAAC;YACrD;QACF;QACA,8GAA8G;QAC9G,IAAIU,iBAAiB7B,UAAU;YAC7B,MAAM,EAAC+C,OAAO,EAAE,GAAGc,cAAa,GAAGhC;YACnCR,OAAOQ,KAAK,CAACkB,SAAS;gBAAC,GAAGc,YAAY;gBAAE1C,MAAM;YAAC;YAC/C;QACF;QAEAL,YAAY,+BAA+Be;QAC3CR,OAAOQ,KAAK,CAAC,+BAA+B;YAACV,MAAM;QAAC;IACtD;AACF"}
|
|
@@ -56,7 +56,7 @@ async function downloadTarStream(url, bearerToken) {
|
|
|
56
56
|
if (!res.body) {
|
|
57
57
|
throw new Error(`Failed to download: ${url}`);
|
|
58
58
|
}
|
|
59
|
-
// eslint-disable-next-line n/no-unsupported-features/node-builtins
|
|
59
|
+
// eslint-disable-next-line n/no-unsupported-features/node-builtins, @typescript-eslint/no-explicit-any
|
|
60
60
|
return Readable.fromWeb(res.body);
|
|
61
61
|
}
|
|
62
62
|
export function checkIsRemoteTemplate(templateName) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\nimport {Readable} from 'node:stream'\nimport {pipeline} from 'node:stream/promises'\n\nimport {subdebug} from '@sanity/cli-core'\nimport {type SanityClient} from '@sanity/client'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {x} from 'tar'\n\nimport {readPackageJson} from '../../util/readPackageJson.js'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\nconst API_READ_TOKEN_ROLE = 'viewer'\nconst API_WRITE_TOKEN_ROLE = 'editor'\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (URL.canParse(value) === false) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(url: string, bearerToken?: string): Promise<Readable> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n return Readable.fromWeb(res.body as any)\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n\nexport async function generateSanityApiToken(\n client: SanityClient,\n label: string,\n type: 'read' | 'write',\n projectId: string,\n): Promise<string> {\n // const client = await getGlobalCliClient({\n // apiVersion: 'v2021-06-07',\n // requireUser: true,\n // })\n const response = await client.request<{key: string}>({\n body: {\n label: `${label} (${Date.now()})`,\n roleName: type === 'read' ? API_READ_TOKEN_ROLE : API_WRITE_TOKEN_ROLE,\n },\n method: 'POST',\n uri: `/projects/${projectId}/tokens`,\n })\n return response.key\n}\n\nexport async function setCorsOrigin(\n client: SanityClient,\n origin: string,\n projectId: string,\n): Promise<void> {\n try {\n // const client = await getGlobalCliClient({\n // apiVersion: 'v2021-06-07',\n // requireUser: true,\n // })\n\n await client.withConfig({projectId}).request({\n body: {allowCredentials: true, origin: origin}, // allowCredentials is true to allow for embedded studios if needed\n method: 'POST',\n url: '/cors',\n })\n } catch (error) {\n // Silent fail, it most likely means that the origin is already set\n debug('Failed to set CORS origin', error)\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","readPackageJson","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","API_READ_TOKEN_ROLE","API_WRITE_TOKEN_ROLE","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","tryApplyPackageName","pkg","JSON","stringify","generateSanityApiToken","client","label","response","request","Date","now","roleName","method","uri","key","setCorsOrigin","origin","withConfig","allowCredentials","error"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,QAAQ,QAAO,mBAAkB;AAEzC,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,SAAQC,eAAe,QAAO,gCAA+B;AAE7D,MAAMC,QAAQL,SAAS;AAEvB,MAAMM,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGL,gBAAgB;IACnBM,YAAY;IACZC,aAAa;A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,GAAG,CAAC,CAAC;YACjCC,UAAU9C,SAAS,SAASrD,sBAAsBC;QACpD;QACAmG,QAAQ;QACRC,KAAK,CAAC,UAAU,EAAEpC,UAAU,OAAO,CAAC;IACtC;IACA,OAAO8B,SAASO,GAAG;AACrB;AAEA,OAAO,eAAeC,cACpBV,MAAoB,EACpBW,MAAc,EACdvC,SAAiB;IAEjB,IAAI;QACF,4CAA4C;QAC5C,+BAA+B;QAC/B,uBAAuB;QACvB,KAAK;QAEL,MAAM4B,OAAOY,UAAU,CAAC;YAACxC;QAAS,GAAG+B,OAAO,CAAC;YAC3CpE,MAAM;gBAAC8E,kBAAkB;gBAAMF,QAAQA;YAAM;YAC7CJ,QAAQ;YACRtF,KAAK;QACP;IACF,EAAE,OAAO6F,OAAO;QACd,mEAAmE;QACnEhH,MAAM,6BAA6BgH;IACrC;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\nimport {Readable} from 'node:stream'\nimport {pipeline} from 'node:stream/promises'\n\nimport {subdebug} from '@sanity/cli-core'\nimport {type SanityClient} from '@sanity/client'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {x} from 'tar'\n\nimport {readPackageJson} from '../../util/readPackageJson.js'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\nconst API_READ_TOKEN_ROLE = 'viewer'\nconst API_WRITE_TOKEN_ROLE = 'editor'\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (URL.canParse(value) === false) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(url: string, bearerToken?: string): Promise<Readable> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n // eslint-disable-next-line n/no-unsupported-features/node-builtins, @typescript-eslint/no-explicit-any\n return Readable.fromWeb(res.body as any)\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n\nexport async function generateSanityApiToken(\n client: SanityClient,\n label: string,\n type: 'read' | 'write',\n projectId: string,\n): Promise<string> {\n // const client = await getGlobalCliClient({\n // apiVersion: 'v2021-06-07',\n // requireUser: true,\n // })\n const response = await client.request<{key: string}>({\n body: {\n label: `${label} (${Date.now()})`,\n roleName: type === 'read' ? API_READ_TOKEN_ROLE : API_WRITE_TOKEN_ROLE,\n },\n method: 'POST',\n uri: `/projects/${projectId}/tokens`,\n })\n return response.key\n}\n\nexport async function setCorsOrigin(\n client: SanityClient,\n origin: string,\n projectId: string,\n): Promise<void> {\n try {\n // const client = await getGlobalCliClient({\n // apiVersion: 'v2021-06-07',\n // requireUser: true,\n // })\n\n await client.withConfig({projectId}).request({\n body: {allowCredentials: true, origin: origin}, // allowCredentials is true to allow for embedded studios if needed\n method: 'POST',\n url: '/cors',\n })\n } catch (error) {\n // Silent fail, it most likely means that the origin is already set\n debug('Failed to set CORS origin', error)\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","readPackageJson","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","API_READ_TOKEN_ROLE","API_WRITE_TOKEN_ROLE","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","tryApplyPackageName","pkg","JSON","stringify","generateSanityApiToken","client","label","response","request","Date","now","roleName","method","uri","key","setCorsOrigin","origin","withConfig","allowCredentials","error"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,QAAQ,QAAO,mBAAkB;AAEzC,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,SAAQC,eAAe,QAAO,gCAA+B;AAE7D,MAAMC,QAAQL,SAAS;AAEvB,MAAMM,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGL,gBAAgB;IACnBM,YAAY;IACZC,aAAa;AACf;AAEA,MAAMC,sBAAsB;AAC5B,MAAMC,uBAAuB;AAoB7B,OAAO,SAASC,uBAAuBC,QAAkB;IACvD,MAAM,EAACC,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,QAAQ,EAAC,GAAGJ;IAC3C,OAAO,CAAC,kCAAkC,EAAEI,SAAS,CAAC,EAAED,KAAK,CAAC,EAAEF,OAAO,CAAC,EAAEC,UAAU;AACtF;AAEA,SAASG,sBAAsBC,KAAa;IAC1C,IAAIC,IAAIC,QAAQ,CAACF,QAAQ;QACvB,OAAO;IACT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AO,CAAC;YAC3CpE,MAAM;gBAAC8E,kBAAkB;gBAAMF,QAAQA;YAAM;YAC7CJ,QAAQ;YACRtF,KAAK;QACP;IACF,EAAE,OAAO6F,OAAO;QACd,mEAAmE;QACnEhH,MAAM,6BAA6BgH;IACrC;AACF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type DeployFlags } from '../deploy/types.js';
|
|
2
|
+
import { type AppManifest } from './types.js';
|
|
3
|
+
interface ExtractAppManifestOptions {
|
|
4
|
+
flags: DeployFlags;
|
|
5
|
+
workDir: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
*
|
|
9
|
+
* This functions slightly differently from the studio manifest extraction function.
|
|
10
|
+
* We don't need to parse very complicated information like schemas and tools,
|
|
11
|
+
* and we submit the manifest as a multipart form field instead of writing a file.
|
|
12
|
+
*/
|
|
13
|
+
export declare function extractAppManifest(options: ExtractAppManifestOptions): Promise<AppManifest | undefined>;
|
|
14
|
+
/**
|
|
15
|
+
* App manifests aren't required right now.
|
|
16
|
+
* This function just ensures we're not uploading empty manifests
|
|
17
|
+
* (so we can reduce noise in user-applications)
|
|
18
|
+
*/
|
|
19
|
+
export declare function appManifestHasData(manifest?: AppManifest | null): boolean;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { getCliConfig } from '@sanity/cli-core';
|
|
2
|
+
import { spinner } from '@sanity/cli-core/ux';
|
|
3
|
+
import { getErrorMessage } from '../../util/getErrorMessage.js';
|
|
4
|
+
/**
|
|
5
|
+
*
|
|
6
|
+
* This functions slightly differently from the studio manifest extraction function.
|
|
7
|
+
* We don't need to parse very complicated information like schemas and tools,
|
|
8
|
+
* and we submit the manifest as a multipart form field instead of writing a file.
|
|
9
|
+
*/ export async function extractAppManifest(options) {
|
|
10
|
+
const { workDir } = options;
|
|
11
|
+
const spin = spinner('Extracting manifest').start();
|
|
12
|
+
try {
|
|
13
|
+
const { app } = await getCliConfig(workDir);
|
|
14
|
+
if (!app) {
|
|
15
|
+
// this is probably a problem for deployment, but not an issue for manifest extraction
|
|
16
|
+
spin.succeed('No app configuration found');
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
const manifest = {
|
|
20
|
+
version: '1',
|
|
21
|
+
...app.icon ? {
|
|
22
|
+
icon: app.icon
|
|
23
|
+
} : {},
|
|
24
|
+
...app.title ? {
|
|
25
|
+
title: app.title
|
|
26
|
+
} : {}
|
|
27
|
+
};
|
|
28
|
+
spin.succeed(`Extracted manifest`);
|
|
29
|
+
return manifest;
|
|
30
|
+
} catch (err) {
|
|
31
|
+
const message = getErrorMessage(err);
|
|
32
|
+
spin.fail(message);
|
|
33
|
+
throw err;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* App manifests aren't required right now.
|
|
38
|
+
* This function just ensures we're not uploading empty manifests
|
|
39
|
+
* (so we can reduce noise in user-applications)
|
|
40
|
+
*/ export function appManifestHasData(manifest) {
|
|
41
|
+
if (!manifest || typeof manifest !== 'object' || Object.keys(manifest).length === 0) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
const validAppManifestKeys = [
|
|
45
|
+
'icon',
|
|
46
|
+
'title'
|
|
47
|
+
];
|
|
48
|
+
return validAppManifestKeys.some((key)=>!!manifest[key]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=extractAppManifest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/manifest/extractAppManifest.ts"],"sourcesContent":["import {getCliConfig} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {getErrorMessage} from '../../util/getErrorMessage.js'\nimport {type DeployFlags} from '../deploy/types.js'\nimport {type AppManifest} from './types.js'\n\ninterface ExtractAppManifestOptions {\n flags: DeployFlags\n workDir: string\n}\n\n/**\n *\n * This functions slightly differently from the studio manifest extraction function.\n * We don't need to parse very complicated information like schemas and tools,\n * and we submit the manifest as a multipart form field instead of writing a file.\n */\nexport async function extractAppManifest(options: ExtractAppManifestOptions): Promise<AppManifest | undefined> {\n const {workDir} = options\n\n const spin = spinner('Extracting manifest').start()\n\n try {\n const {app} = await getCliConfig(workDir)\n if (!app) {\n // this is probably a problem for deployment, but not an issue for manifest extraction\n spin.succeed('No app configuration found')\n return undefined\n }\n const manifest: AppManifest = {\n version: '1',\n ...(app.icon ? {icon: app.icon} : {}),\n ...(app.title ? {title: app.title} : {}),\n }\n\n spin.succeed(`Extracted manifest`)\n\n return manifest\n } catch (err) {\n const message = getErrorMessage(err)\n spin.fail(message)\n throw err\n }\n}\n\n/**\n * App manifests aren't required right now.\n * This function just ensures we're not uploading empty manifests\n * (so we can reduce noise in user-applications)\n */\nexport function appManifestHasData(manifest?: AppManifest | null): boolean {\n if (!manifest || typeof manifest !== 'object' || Object.keys(manifest).length === 0) {\n return false\n }\n const validAppManifestKeys = ['icon', 'title']\n return validAppManifestKeys.some((key) => !!manifest[key as keyof AppManifest])\n}\n"],"names":["getCliConfig","spinner","getErrorMessage","extractAppManifest","options","workDir","spin","start","app","succeed","undefined","manifest","version","icon","title","err","message","fail","appManifestHasData","Object","keys","length","validAppManifestKeys","some","key"],"mappings":"AAAA,SAAQA,YAAY,QAAO,mBAAkB;AAC7C,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,eAAe,QAAO,gCAA+B;AAS7D;;;;;CAKC,GACD,OAAO,eAAeC,mBAAmBC,OAAkC;IACzE,MAAM,EAACC,OAAO,EAAC,GAAGD;IAElB,MAAME,OAAOL,QAAQ,uBAAuBM,KAAK;IAEjD,IAAI;QACF,MAAM,EAACC,GAAG,EAAC,GAAG,MAAMR,aAAaK;QACjC,IAAI,CAACG,KAAK;YACR,sFAAsF;YACtFF,KAAKG,OAAO,CAAC;YACb,OAAOC;QACT;QACA,MAAMC,WAAwB;YAC5BC,SAAS;YACT,GAAIJ,IAAIK,IAAI,GAAG;gBAACA,MAAML,IAAIK,IAAI;YAAA,IAAI,CAAC,CAAC;YACpC,GAAIL,IAAIM,KAAK,GAAG;gBAACA,OAAON,IAAIM,KAAK;YAAA,IAAI,CAAC,CAAC;QACzC;QAEAR,KAAKG,OAAO,CAAC,CAAC,kBAAkB,CAAC;QAEjC,OAAOE;IACT,EAAE,OAAOI,KAAK;QACZ,MAAMC,UAAUd,gBAAgBa;QAChCT,KAAKW,IAAI,CAACD;QACV,MAAMD;IACR;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASG,mBAAmBP,QAA6B;IAC9D,IAAI,CAACA,YAAY,OAAOA,aAAa,YAAYQ,OAAOC,IAAI,CAACT,UAAUU,MAAM,KAAK,GAAG;QACnF,OAAO;IACT;IACA,MAAMC,uBAAuB;QAAC;QAAQ;KAAQ;IAC9C,OAAOA,qBAAqBC,IAAI,CAAC,CAACC,MAAQ,CAAC,CAACb,QAAQ,CAACa,IAAyB;AAChF"}
|