GithubHelp home page GithubHelp logo

prismicio / prismic-types Goto Github PK

View Code? Open in Web Editor NEW
11.0 7.0 4.0 1.8 MB

Type definitions for Prismic content, models, and APIs

Home Page: https://prismic.io/docs/technologies/javascript

License: Apache License 2.0

JavaScript 0.54% TypeScript 99.46%
prismic javascript typescript

prismic-types's Introduction

Note: This package has been merged into @prismicio/client ≥ v7.

This package and repository will no longer be updated, except in special circumstances.

@prismicio/types

npm version npm downloads Github Actions CI Codecov Conventional Commits License

⚠ This project is in an experimental state and therefore primarily meant to be used by Prismic kits. Use it at your own risks or stay tuned for the official release!

Type definitions for Prismic related structure.

  • 📄  Per-field type definitions;
  • 🌐  Dedicated GraphQL API support.

Install

npm install --save-dev @prismicio/types

Documentation

To discover what's new on this package check out the changelog. For full documentation, visit the official Prismic documentation.

Contributing

Whether you're helping us fix bugs, improve the docs, or spread the word, we'd love to have you as part of the Prismic developer community!

Asking a question: Open a new topic on our community forum explaining what you want to achieve / your question. Our support team will get back to you shortly.

Reporting a bug: Open an issue explaining your application's setup and the bug you're encountering.

Suggesting an improvement: Open an issue explaining your improvement or feature so we can discuss and learn more.

Submitting code changes: For small fixes, feel free to open a pull request with a description of your changes. For large changes, please first open an issue so we can discuss if and how the changes should be implemented.

For more clarity on this project and its structure you can also check out the detailed CONTRIBUTING.md document.

License

   Copyright 2013-2022 Prismic <[email protected]> (https://prismic.io)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

prismic-types's People

Contributors

angeloashmore avatar dayhaysoos avatar lihbr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

prismic-types's Issues

More detailed TSDocs on customType.ts

/**
* A Custom Type's tab. Each tab can contain any number of fields but is limited to one Slice Zone.
*
* @typeParam FieldName API IDs of the fields.
*/

  • CustomTypeModelBooleanField
  • CustomTypeModelColorField
  • CustomTypeModelDateField
  • CustomTypeModelEmbedField
  • CustomTypeModelGeoPointField
  • CustomTypeModelGroupField
  • CustomTypeModelImageField
  • CustomTypeModelImageConstraint
  • CustomTypeModelIntegrationField
  • CustomTypeModelLinkSelectType
  • CustomTypeModelLinkSelectType
  • CustomTypeModelLinkField
  • CustomTypeModelLinkToMediaField
  • CustomTypeModelNumberField
  • CustomTypeModelSelectField
  • CustomTypeModelRichTextField
  • CustomTypeModelRichTextMultiField
  • CustomTypeModelRichTextSingleField
  • CustomTypeModelKeyTextField
  • CustomTypeModelTimestampField
  • CustomTypeModelUIDField
  • CustomTypeModelSliceZoneField
  • CustomTypeModelSliceLabel
  • CustomTypeModelSliceType
  • SharedSliceModel
  • SharedSliceModelVariation

Add LinkResolver, ResolvedApi, ApiSearchResponse types

Is your feature request related to a problem? Please describe.

Hey people, i wish you all well.

I have a internal package on company to make some queries that isn't available on @prismicio/client and other queries that are used by a lot of projects. We created this package to unify the code on a unique place.

So, i updated the @prismicio/client to v6 and added @prismicio/types and i realized that some types had gone.

Some of them:

LinkResolver, ResolvedApi, ApiSearchRespons, QueryOptions

Describe the solution you'd like

I would like to know why these types were removed on v6 because i

Describe alternatives you've considered

Open a issue on this repository ;)

Why "complex" Union type for content relationship field while it could simply be a Maybe (Value | null)?

When im using the auto generated types i noticed for example:

const relatedFaq: EmptyLinkField<"Document"> | FilledContentRelationshipField<"faq", string, never>

where the emptyLinkField is not much like:

{ link_type: 'Document' }

my question is why you don't just pass null in that case? It makes it also way easier to consume down the line with if else. An empty document is not adding any value

Changes of types for RichTextNodeType breaks other PrismicIO library

Versions

  • @prismicio/types: v0.1.18
  • node: v10.16.0

Reproduction

With the change in 0.1.18 of the RichTextNodeType type from an enum to a const variable, the import and export in @prismicio/richtext is not working anymore.

If you have @prismicio/richtext with version 2.0.0-beta.1, and your version of @prismicio/types is 0.1.18, you will have an issue with your types (especially if you try to compile).

Additional Details

Here is the interesting part of my package-lock.json :

"@prismicio/client": {
      "version": "6.0.0-beta.3",
      "resolved": "https://registry.npmjs.org/@prismicio/client/-/client-6.0.0-beta.3.tgz",
      "integrity": "sha512-AZn0u5Ah6q4PGAlGvKyVSv3OfAbM1DjGpbZWedkMiBGJ6t/tB5GyaIh2Znsfdkw8QuL80041yURdsGXaQeE2HQ==",
      "requires": {
        "@prismicio/helpers": "^2.0.0-beta.0",
        "@prismicio/types": "^0.1.15"
      }
    },
    "@prismicio/helpers": {
      "version": "2.0.0-beta.3",
      "resolved": "https://registry.npmjs.org/@prismicio/helpers/-/helpers-2.0.0-beta.3.tgz",
      "integrity": "sha512-YaMRZ6JBb9f/+BXWq9V+xSQGOnWK3+8ebKi9GSeOjit+JOEZDSBn0hE87j6X7wp8cG5KTqXyBXsmd2vOh8IhdA==",
      "requires": {
        "@prismicio/richtext": "^2.0.0-beta.1",
        "@prismicio/types": "^0.1.17",
        "escape-html": "^1.0.3"
      }
    },
    "@prismicio/richtext": {
      "version": "2.0.0-beta.1",
      "resolved": "https://registry.npmjs.org/@prismicio/richtext/-/richtext-2.0.0-beta.1.tgz",
      "integrity": "sha512-9LA+dcEtncprfjpPdQWsRThuFpDA0ID1Ne0yJJHVlKKl9qUDDfV7fbN714W2dxEV2zWRip/lyLlnfMOAABjE/w==",
      "requires": {
        "@prismicio/types": "^0.1.15"
      }
    },
    "@prismicio/types": {
      "version": "0.1.18",
      "resolved": "https://registry.npmjs.org/@prismicio/types/-/types-0.1.18.tgz"
    },

Steps to reproduce

I try to compile my code with the following command :
npx tsc --outDir dist
And I get the following error :

node_modules/@prismicio/richtext/dist/index.d.ts:10:62 - error TS2749: 'RichTextNodeType' refers to a value, but is being used as a type here. Did you mean 'typeof RichTextNodeType'?

10 declare type RichTextFunctionSerializer<ReturnType> = (type: RichTextNodeType, node: RTAnyNode, text: string | undefined, children: ReturnType[], key: string) => ReturnType | null | undefined;
                                                                ~~~~~~~~~~~~~~~~

node_modules/@prismicio/richtext/dist/index.d.ts:59:11 - error TS2749: 'RichTextNodeType' refers to a value, but is being used as a type here. Did you mean 'typeof RichTextNodeType'?

59     type: RichTextNodeType;
             ~~~~~~~~~~~~~~~~

What is expected?

The compilation should work as intended

What is actually happening?

With the change in 0.1.18 of the RichTextNodeType type from an enum to a const variable, the import and export in @prismicio/richtext is not working anymore.

Include `data` field in RelationField

Is your feature request related to a problem? Please describe.

The data field does not exist on RelationField. Using the REST API, one can query for a document using fetchLinks or graphQuery. This populates the data field on the document.

Currently, we can only create a field type like the following:

type MyField = RelationField<"page", "en-us">;
type MyFieldData = MyField["data"];

data on MyField does not exist, causing the line with MyFieldData to throw a type error.

Describe the solution you'd like

The ability to provide the data field's type via a third generic could solve this.

type MyField = RelationField<
  "page",
  "en-us",
  {
    requestedDataField: KeyTextField,
  }
>;
type MyFieldData = MyField["data"];

RichTextField is broken

Versions

  • @prismicio/types: ^0.2.7
  • node: 16.10

Reproduction

import { RichTextField } from '@prismicio/types';
import { PrismicRichText } from '@prismicio/react';

interface CurrentSlice extends Slice {
  primary: {
    column_one: RichTextField;
    column_two: RichTextField;
  };
}
<PrismicRichText field={slice.primary.column_one} components={richTextComponents} />

I get the following error:

Type '[] | [import("/Users/kris/Documents/code/honeynjam/robocorp/robocorp-com/node_modules/@prismicio/types/dist/value/richText").RTNode, ...import("/Users/kris/Documents/code/honeynjam/robocorp/robocorp-com/node_modules/@prismicio/types/dist/value/richText").RTNode[]]' is not assignable to type '[] | [import("/Users/kris/Documents/code/honeynjam/robocorp/robocorp-com/node_modules/@prismicio/client/node_modules/@prismicio/types/dist/index").RTNode, ...import("/Users/kris/Documents/code/honeynjam/robocorp/robocorp-com/node_modules/@prismicio/client/node_modules/@prismicio/types/dist/index").RTNode[]]'.
  Type '[RTNode, ...RTNode[]]' is not assignable to type '[] | [RTNode, ...RTNode[]]'.ts(2322)
index.d.ts(265, 5): The expected type comes from property 'field' which is declared here on type 'IntrinsicAttributes & PrismicRichTextProps<LinkResolverFunction<string>>'

If I use the TitleField, I don't get any errors but this is obviously the wrong field to use.

What is expected?

To work without any errors

What is actually happening?

I get a typescript error

Array types are incompatible

Is your feature request related to a problem? Please describe.

I am a bit frustrated with the use of this pattern:

State extends "empty" ? [] : [RTNode, ...RTNode[]]

In my code, I have custom types holding data like nodes: RTNode[] or slices: Slice[]. However, these types are not compatible with [] | [RTNode, ...RTNode[]].

I would love to hear more context about this pattern and why did you decide to use it instead of never[] | RTNode[].

Describe the solution you'd like

Ideally, Typescript would understand that [] | [RTNode, ...RTNode[]] is equivalent to RTNode[] (both ways). Until then I would prefer simpler types without this State (e.g. never[] | RTNode[])

Add tests

Is your feature request related to a problem? Please describe.

The library currently does not contain tests. The types should be tested against known-good data shapes.

Describe the solution you'd like

Create .ts files that are typed using the library's definitions. If the .ts files can be compiled with tsc, the tests pass.

For example, testing SelectField could look like this:

const filledSelectField1: prismicT.SelectField<"Option 1" | "Option 2", "filled"> = "Option 1"
const filledSelectField2: prismicT.SelectField<"Option 1" | "Option 2", "filled"> = "Option 2"
const emptySelectField: prismicT.SelectField<"Option 1" | "Option 2", "empty"> = null

// @ts-expect-error
const filledSelectField3: prismicT.SelectField<"Option 1" | "Option 2", "filled"> = "Option 3"
// @ts-expect-error
const filledSelectField4: prismicT.SelectField<"Option 1" | "Option 2", "filled"> = null

Describe alternatives you've considered

None.

Additional context

N/A

prismic.predicate.not type

Versions

  • @prismicio/types: 0.1.27
  • @prismicio/client": "6.4.3",

Reproduction

It looks like the types for prismic.predicate.not and for some others are incorrect.

it's expected the single value
image

but in this case prismic API return error :

image

and the correct one is using array :

image

Detailed TSDocs for fields.ts

https://github.com/prismicio/prismic-types/blob/master/src/fields.ts

  • RTTextNodeBase
  • RTHeading1Node
  • RTHeading2Node
  • RTHeading3Node
  • RTHeading4Node
  • RTHeading5Node
  • RTHeading6Node
  • RTParagraphNode
  • RTPreformattedNode
  • RTListItemNode
  • RTOListItemNode
  • RTSpanNodeBase
  • RTStrongNode
  • RTEmNode
  • RTLabelNode
  • RTImageNode
  • RTEmbedNode
  • RTListNode
  • RTOListNode
  • ImageField
  • LinkType
  • FilledLinkToDocumentField
  • FilledLinkToWebField
  • FilledLinkToMediaField
  • RelationField
  • LinkField
  • LinkToMediaField
  • EmbedField
  • GroupField
  • IntegrationField
  • Slice
  • SliceZone

`SharedSliceVariation` doesn't have `slice_type`

Versions

  • @prismicio/types: @0.1.29
  • node: 16.14.2

Reproduction

image

Steps to reproduce

Just use the type

What is expected?

The type to have a definition for slice_type.

What is actually happening?

The type doesn't have a definition for slice_type

Input attributes + Typescript

I have an interface:

interface Input {
  type: "input" | "input-email" | "textarea";
  name: KeyTextField;
  label: KeyTextField;
  placeholder: KeyTextField;
  required: boolean
}

I get the following Typescript error for the following attributes

  • label -> htmlFor
  • input/textarea -> name
  • input/textarea -> id
  • input/textarea -> placeholder
Type 'string | null' is not assignable to type 'string | undefined'.ts(2322)
[index.d.ts(2216, 9): ]()The expected type comes from property 'placeholder' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'

In order to fix the error, I had to update my Props

interface Input {
  type: "input" | "input-email" | "text-area";
  name: string | undefined;
  label: string | undefined;
  placeholder: string | undefined;
  required: boolean;
}

Is it possible to update the KeyTextField?

Add webhook response types

Is your feature request related to a problem? Please describe.

Consumers of Prismic's webhooks currently do not have an official way to type the incoming data. Developers will need to write the types in their own projects.

Describe the solution you'd like

@prismicio/types can provide these types to developers. As the API changes, or new webhooks are added, this library can be updated to ensure developers have the latest types.

Describe alternatives you've considered

Developers can write these types in their own project. They can also minimize the types to include only what is relevant to their application. This can lead to extra friction when adopting Prismic webhooks into an application as it requires additional work.

Additional context

The following types are taken from gatsby-source-prismic and could be used as a reference when adding to this library.

(Based on types from @MarcMcIntosh)

export type PrismicWebhookBody =
  | PrismicWebhookBodyApiUpdate
  | PrismicWebhookBodyTestTrigger

export enum PrismicWebhookType {
  APIUpdate = 'api-update',
  TestTrigger = 'test-trigger',
}

interface PrismicWebhookBodyBase {
  type: PrismicWebhookType
  domain: string
  apiUrl: string
  secret: string | null
}

export interface PrismicWebhookBodyApiUpdate extends PrismicWebhookBodyBase {
  type: PrismicWebhookType.APIUpdate
  masterRef?: string
  releases: PrismicWebhookOperations<PrismicWebhookRelease>
  masks: PrismicWebhookOperations<PrismicWebhookMask>
  tags: PrismicWebhookOperations<PrismicWebhookTag>
  documents: string[]
  // eslint-disable-next-line deprecation/deprecation
  experiments?: PrismicWebhookOperations<PrismicWebhookExperiment>
}

export interface PrismicWebhookBodyTestTrigger extends PrismicWebhookBodyBase {
  type: PrismicWebhookType.TestTrigger
}

interface PrismicWebhookOperations<T> {
  update?: T[]
  addition?: T[]
  deletion?: T[]
}

interface PrismicWebhookMask {
  id: string
  label: string
}

interface PrismicWebhookTag {
  id: string
}

export interface PrismicWebhookRelease {
  id: string
  ref: string
  label: string
  documents: string[]
}

/**
 * @deprecated
 */
interface PrismicWebhookExperiment {
  id: string
  name: string
  // eslint-disable-next-line deprecation/deprecation
  variations: PrismicWebhookExperimentVariation[]
}

/**
 * @deprecated
 */
interface PrismicWebhookExperimentVariation {
  id: string
  ref: string
  label: string
}

Libraries using `@prismicio/types` with different versions results in type errors

Versions

  • @prismicio/types: v0.1.15
  • node: v14.17.0

Reproduction

This is difficult to reproduce so I'll share a general proof.

enum A {
	foo = "foo",
}

enum B {
	foo = "foo",
}

const val: A.foo = B.foo;
// [tsserver 2322] [E] Type 'B' is not assignable to type 'A'.

Despite A.foo and B.foo having equivalent literal values, TypeScript treats them as distinct types.

In the types library, this scenario happens when dependent libraries resolve different @prismicio/types installations. More specifically, when the RichTextNodeType enum exists in more than one location, TypeScript sees them as incompatible.

The following node_modules structure produces this:

  • node_modules/@prismicio/types
  • node_modules/@prismicio/mock/node_modules/@prismicio/types

This occurs when packages resolve to different versions of @prismicio/types, thus requiring dependent packages to install their own version of @prismicio/types.

Steps to reproduce

I'm having trouble finding reproducible steps that cause this, but indeed it happens:

image

What is expected?

Type errors do not occur when multiple versions of @prismicio/types are installed. Type errors due to structural differences between versions are expected.

What is actually happening?

Multiple versions cause enum incompatibilities. See the above example errors.

asImageWidthSrcSet does not accept ImageField

asImageWidthSrcSet expects an ImageFieldImage, but in the docs it appears to be accepting an ImageField.

Reproduction

import { asImageWidthSrcSet } from "@prismicio/helpers"
import * as prismicT from "@prismicio/types"

const image = {} as prismicT.ImageField
asImageWidthSrcSet(image) // Argument of type 'ImageField<never, FieldState>' is not assignable to parameter of type 'EmptyImageFieldImage | FilledImageFieldImage'.

`IntegrationFields` is incorrect - it should only contain third-party data

Versions

  • @prismicio/types: v0.1.27
  • node: v16.15.0

What is expected?

The IntegrationFields type should only include third-party data.

import * as prismicT from '@prismicio/types'

type ShopifyField = prismicT.IntegrationField<{ product_id: string }>

ShopifyField should be equivalent to { product_id: string } | null.

Without providing a type parameter, IntegrationField could default to something like Record<string, unknown> | null.

What is actually happening?

IntegrationField currently includes other properties like id, title, and image_url. It nests the third-party data under a blob property.

prismic-types/src/fields.ts

Lines 793 to 800 in 97714c3

: {
id: string;
title?: string;
description?: string;
image_url?: string;
last_update: number;
blob: Blob;
};

This data shape is actually for the Integration Fields API.

(Thanks to @chamois-d-or for discovering this error!)

Slice type: Slice Simulator x Slice Zone(s) type mismatch

When typing slices with TypeScript, SliceZone(s) infers their types from the components map prop. This causes a type mismatch from slices provided by Slice Simulator as that cannot be typed(?).

See:

What is expected?

Slice array provided by Slice Simulator should match expected SliceZone slices prop type when slice components are typed.

What is actually happening?

Slice array provided by Slice Simulator doesn't match expected SliceZone slices prop type when slice components are typed.

Potential fixes?

I'm posting this issue here as I'm not sure which kit it really belongs to. I can see few fixes but I don't really like them:

  • Typing the slice array provided by Slice Simulator as any;
  • Extending the type from SliceZone(s) to always allow for "any slice" on top of "known slices"

"field" attributes of the RichText breaking

Versions

  • @prismicio/types: 0.2.4
  • node: 16.13.1

Context

Hi everyone, I've been trying to update the last version of prismic-types, but I came across an issue on the RichText as you can see on the screenshot below:
CleanShot 2022-11-29 at 10 55 39@2x

This error only appears when I try to update this library, so I guess this is related.

Here is the full report from Typescript:

Type '[] | [RTNode, ...RTNode[]]' is not assignable to type '[] | [RTNode, ...RTNode[]] | null | undefined'.
  Type '[RTNode, ...RTNode[]]' is not assignable to type '[] | [RTNode, ...RTNode[]] | null | undefined'.
    Type '[import("{my_nodemodules_path}/@prismicio/types/dist/index").RTNode, ...import("{my_nodemodules_path}/@prismicio/types/dist/index").RTNode[]]' is not assignable to type '[import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTNode, ...import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTNode[]]'.
      Type at position 0 in source is not compatible with type at position 0 in target.
        Type 'import("{my_nodemodules_path}/@prismicio/types/dist/index").RTNode' is not assignable to type 'import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTNode'.
          Type 'RTHeading1Node' is not assignable to type 'RTNode'.
            Type 'import("{my_nodemodules_path}/@prismicio/types/dist/index").RTHeading1Node' is not assignable to type 'import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTHeading1Node'.
              Types of property 'spans' are incompatible.
                Type 'import("{my_nodemodules_path}/@prismicio/types/dist/index").RTInlineNode[]' is not assignable to type 'import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTInlineNode[]'.
                  Type 'import("{my_nodemodules_path}/@prismicio/types/dist/index").RTInlineNode' is not assignable to type 'import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTInlineNode'.
                    Type 'RTLinkNode' is not assignable to type 'RTInlineNode'.
                      Type 'import("{my_nodemodules_path}/@prismicio/types/dist/index").RTLinkNode' is not assignable to type 'import("{my_nodemodules_path}}/@prismicio/types/dist/index").RTLinkNode'.
                        Types of property 'data' are incompatible.
                          Type 'FilledContentRelationshipField<string, string, unknown> | FilledLinkToWebField | FilledLinkToMediaField' is not assignable to type 'FilledContentRelationshipField<string, string, never> | FilledLinkToWebField | FilledLinkToMediaField'.
                            Type 'FilledContentRelationshipField<string, string, unknown>' is not assignable to type 'FilledContentRelationshipField<string, string, never> | FilledLinkToWebField | FilledLinkToMediaField'.
                              Type 'FilledContentRelationshipField<string, string, unknown>' is not assignable to type 'FilledContentRelationshipField<string, string, never>'.
                                Types of property 'data' are incompatible.
                                  Type 'unknown' is not assignable to type 'undefined'.

Any idea what I'm missing here? Thanks 🙏

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.