The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Port genql 3.0.5 test suite and run twenty-client-sdk tests in CI (#25092)
Paul Rastoinb88e49126d31
diff --git a/.github/workflows/ci-client-sdk.yaml b/.github/workflows/ci-client-sdk.yamlnew file mode 100644index 00000000000..b57ef91e349--- /dev/null+++ b/.github/workflows/ci-client-sdk.yaml@@ -0,0 +1,55 @@+name: CI Client SDK++on:+ pull_request:+ merge_group:++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}++jobs:+ changed-files-check:+ if: github.event_name != 'merge_group'+ uses: ./.github/workflows/changed-files.yaml+ with:+ files: |+ packages/twenty-client-sdk/**+ packages/twenty-shared/**+ yarn.lock+ .github/workflows/ci-client-sdk.yaml+ !packages/twenty-client-sdk/package.json+ client-sdk-test:+ needs: changed-files-check+ if: needs.changed-files-check.outputs.any_changed == 'true'+ timeout-minutes: 30+ runs-on: ubuntu-latest+ env:+ NODE_OPTIONS: '--max-old-space-size=4096'+ strategy:+ matrix:+ task: [lint, typecheck, test]+ steps:+ - name: Fetch custom Github Actions and base branch history+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1+ with:+ fetch-depth: 10+ - name: Install dependencies+ uses: ./.github/actions/yarn-install+ - name: Run ${{ matrix.task }} task+ uses: ./.github/actions/nx-affected+ with:+ tag: scope:client-sdk+ tasks: ${{ matrix.task }}+ ci-client-sdk-status-check:+ if: always() && !cancelled()+ timeout-minutes: 5+ runs-on: ubuntu-latest+ needs: [changed-files-check, client-sdk-test]+ steps:+ - name: Fail job if any needs failed+ if: contains(needs.*.result, 'failure')+ run: exit 1diff --git a/.github/workflows/ci-sdk.yaml b/.github/workflows/ci-sdk.yamlindex 938161b8c73..984a3650b6c 100644--- a/.github/workflows/ci-sdk.yaml+++ b/.github/workflows/ci-sdk.yaml@@ -18,9 +18,11 @@ jobs:with:files: |packages/twenty-sdk/**+ packages/twenty-client-sdk/**packages/twenty-server/**.github/workflows/ci-sdk.yaml!packages/twenty-sdk/package.json+ !packages/twenty-client-sdk/package.jsonsdk-test:needs: changed-files-checkif: needs.changed-files-check.outputs.any_changed == 'true'diff --git a/packages/twenty-client-sdk/project.json b/packages/twenty-client-sdk/project.jsonindex d97d8fe966f..a7342268a48 100644--- a/packages/twenty-client-sdk/project.json+++ b/packages/twenty-client-sdk/project.json@@ -3,7 +3,7 @@"$schema": "../../node_modules/nx/schemas/project-schema.json","sourceRoot": "packages/twenty-client-sdk/src","projectType": "library",- "tags": ["scope:sdk"],+ "tags": ["scope:client-sdk"],"targets": {"build": {"executor": "nx:run-commands",@@ -32,9 +32,14 @@},"test": {"executor": "@nx/vitest:test",- "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],+ "dependsOn": ["^build"],"options": {"config": "{projectRoot}/vitest.config.ts"+ },+ "configurations": {+ "ci": {+ "watch": false+ }}},"set-local-version": {},diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/README.md b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/README.mdnew file mode 100644index 00000000000..0971fc2815e--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/README.md@@ -0,0 +1,47 @@+# Ported genql 3.0.5 test suite++Port of the test suite of [`remorses/genql`](https://github.com/remorses/genql)+at `@genql/[email protected]` (commit `4a547db46a9a614cc2b5958e28674af351898464`), the+version the codegen in `../../genql` was vendored from. It protects the+vendored engine's behavior; the engine's output bytes are pinned by+`../genql-engine-output.test.ts` and by the checked-in `fixture/generated/`+client (`generated-fixture-drift.test.ts`).++| Here | Upstream |+| --- | --- |+| `fixture/schema.graphql` | `integration-tests/schema.graphql` (byte-verbatim) |+| `fixture/generated/` | output of the vendored engine for that schema, checked in so type-level assertions compile; pinned by `generated-fixture-drift.test.ts` |+| `generate-queries.test.ts` | `integration-tests/tests/simple.ts` |+| `execute-queries.test.ts` | `integration-tests/tests/execution.ts` |+| `type-selection.test.ts` | `cli/src/typeSelection.test.ts` |+| `type-map.test.ts` | `cli/src/render/typeMap/index.test.ts` |+| `render-typing.test.ts` | `cli/src/render/common/__tests__/renderTyping.test.ts` |+| `comment.test.ts` | `cli/src/render/common/__tests__/comment.test.ts` |+| `render-context.test.ts` | `cli/src/render/common/__tests__/RenderContext.test.ts` |+| `render-schema.test.ts` | `cli/src/render/schema/renderSchema.test.ts` |+| `render-test-helpers.ts` | `cli/src/testHelpers/render.ts` |++Not ported: `parse.test.ts` and `printer.test.ts` (they cover CLI/printer code+Twenty did not vendor) and the subscription suite (already skipped upstream).++## Adaptations++Selections, resolvers, assertions and test names are upstream's. What changed:++- **mocha/sucrase/snap-shot-it → vitest.** Snapshots are vitest snapshots.+- **apollo-server (v3, deprecated) → graphql-js execution.** `execution.ts`+ booted a real HTTP server per test; `execute-queries.test.ts` runs the same+ resolvers through `graphql()` behind an injected `fetch`/`fetcher`, which+ exercises the identical client code path with no network and no new+ dependency.+- **tsd `expectType` → vitest `expectTypeOf`, strengthened to exact.**+ Upstream's CI did typecheck its integration tests (its `gen` step ran+ `tsc --noEmit` over tests plus a freshly generated client), but it never ran+ the tsd CLI — and under plain tsc, tsd's `expectType<T>(value)` degrades to+ an assignability check. Several assertions were therefore looser than the+ real types. The exact assertions here pin what the 3.0.5 engine actually+ generates (fields absent from a response are `undefined`, never `null`;+ `__typename` is a literal type) and are enforced by the package typecheck.+- **`type-map.test.ts` assertions enabled.** Upstream ran them in+ output-logging mode with stale expected values; the values here match the+ engine's actual output.diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/__snapshots__/generate-queries.test.ts.snap b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/__snapshots__/generate-queries.test.ts.snapnew file mode 100644index 00000000000..e9a7b240a36--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/__snapshots__/generate-queries.test.ts.snap@@ -0,0 +1,191 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`generate queries > do not fetch falsy fields 1`] = `+"subscription {+ user {+ name+ }+}+"+`;++exports[`generate queries > do not fetch falsy fields with __scalar 1`] = `+"subscription {+ user {+ ...f1+ }+}+fragment f1 on User {+ name+ __typename+}+"+`;++exports[`generate queries > many 1`] = `+"query ($v1: String!, $v2: String) {+ repository(name: $v1, owner: $v2) {+ createdAt+ forks {+ edges {+ cursor+ node {+ ...f1+ }+ }+ }+ }+ user {+ ...f2+ }+}+fragment f1 on Fork {+ name+ number+ __typename+}+fragment f2 on User {+ name+ common+ __typename+}+"+`;++exports[`generate queries > optional arg 1`] = `+"query {+ optionalArgs {+ createdAt+ forks {+ edges {+ cursor+ node {+ ...f1+ }+ }+ }+ }+}+fragment f1 on Fork {+ name+ number+ __typename+}+"+`;++exports[`generate queries > query 1`] = `+"query ($v1: String!, $v2: String) {+ repository(name: $v1, owner: $v2) {+ createdAt+ forks {+ edges {+ cursor+ node {+ ...f1+ }+ }+ }+ }+}+fragment f1 on Fork {+ name+ number+ __typename+}+"+`;++exports[`generate queries > recursive type 1`] = `+"query {+ recursiveType {+ value+ recurse {+ recurse {+ value+ recurse {+ recurse {+ ...f3+ }+ ...f2+ }+ }+ ...f1+ }+ }+}+fragment f1 on RecursiveType {+ value+ __typename+}+fragment f2 on RecursiveType {+ value+ __typename+}+fragment f3 on RecursiveType {+ value+ __typename+}+"+`;++exports[`generate queries > recursive type with args 1`] = `+"query ($v1: [String!], $v2: Int, $v3: Int, $v4: Int) {+ recursiveType(requiredVal: $v1) {+ value+ recurse(arg: $v2) {+ recurse(arg: $v3) {+ value+ recurse(arg: $v4) {+ recurse {+ ...f3+ }+ ...f2+ }+ }+ ...f1+ }+ }+}+fragment f1 on RecursiveType {+ value+ __typename+}+fragment f2 on RecursiveType {+ value+ __typename+}+fragment f3 on RecursiveType {+ value+ __typename+}+"+`;++exports[`generate queries > subscriptions 1`] = `+"subscription {+ user {+ ...f1+ }+}+fragment f1 on User {+ name+ common+ __typename+}+"+`;++exports[`generate queries > use __name operation name 1`] = `+"subscription SomeName {+ user {+ ...f1+ }+}+fragment f1 on User {+ name+ common+ __typename+}+"+`;diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/comment.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/comment.test.tsnew file mode 100644index 00000000000..61eba7c122c--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/comment.test.ts@@ -0,0 +1,42 @@+import { expect, test } from 'vitest';++import { comment } from '../../genql/render/common/comment';++// Port of remorses/[email protected]+// cli/src/render/common/__tests__/comment.test.ts, with common-tags'+// stripIndent replaced by explicit expected strings.+test('deprecated', () => {+ expect(comment({ deprecated: 'deprecation reason' })).toBe(+ '\n/** @deprecated deprecation reason */\n',+ );+});++test('deprecated multiline', () => {+ expect(comment({ deprecated: 'deprecation\nreason\nmultiline' })).toBe(+ '\n/** @deprecated deprecation reason multiline */\n',+ );+});++test('single line', () => {+ expect(comment({ text: 'single line' })).toBe('\n/** single line */\n');+});++test('single line deprecated', () => {+ expect(+ comment({ text: 'single line', deprecated: 'deprecation reason' }),+ ).toBe('\n/**\n * @deprecated deprecation reason\n * single line\n */\n');+});++test('multiline', () => {+ expect(comment({ text: 'multiline\ntext' })).toBe(+ '\n/**\n * multiline\n * text\n */\n',+ );+});++test('multiline deprecated', () => {+ expect(+ comment({ text: 'multiline\ntext', deprecated: 'deprecation reason' }),+ ).toBe(+ '\n/**\n * @deprecated deprecation reason\n * multiline\n * text\n */\n',+ );+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/execute-queries.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/execute-queries.test.tsnew file mode 100644index 00000000000..f9bfbf02e31--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/execute-queries.test.ts@@ -0,0 +1,459 @@+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ buildSchema,+ graphql,+ type ExecutionResult,+ type GraphQLSchema,+} from 'graphql';+import { describe, expect, expectTypeOf, it, vi } from 'vitest';++import {+ createClient,+ everything,+ GenqlError,+ isHouse,+ type Account,+ type Point,+ type User,+} from './fixture/generated';+import { type GraphqlOperation } from './fixture/generated/runtime';++// Port of remorses/[email protected] integration-tests/tests/execution.ts ("execute+// queries"). Upstream booted an apollo-server (v3, now deprecated) per test;+// here the same resolvers run through graphql-js `graphql()` behind an+// injected `fetch`/`fetcher`, which exercises the identical client code path+// (operation building, POST body, response parsing, batching, errors) without+// a network or any extra dependency. graphql-js resolves the abstract types+// (Account, Point, GenericError) from the `__typename` each resolver returns,+// as apollo did. Selections, assertions and test names are upstream's; tsd's+// `expectType` becomes `expectTypeOf`. The skipped upstream subscription suite+// (already skipped there) is not ported.+//+// One deliberate correction: upstream typechecked this file with plain tsc+// (never the tsd CLI), and under plain tsc tsd's `expectType<T>(value)` is+// only an assignability check — so several assertions were looser than the+// real types. The exact assertions below pin what the 3.0.5 engine actually+// generates: response fields are `undefined` when unset (never `null` —+// honest `| null` response types arrived in genql v4), and `__typename` is a+// literal type, not `string`.++const SCHEMA_PATH = join(+ dirname(fileURLToPath(import.meta.url)),+ 'fixture',+ 'schema.graphql',+);++const executableSchema: GraphQLSchema = buildSchema(+ readFileSync(SCHEMA_PATH, 'utf-8'),+);++const johnUser = {+ name: 'John',+};++// The Query resolvers from upstream's makeServer(), as graphql-js rootValue+// field functions (they receive the field args as first parameter).+const queryRootValue = {+ user: () => johnUser,+ throwsError: () => {+ throw new Error('x');+ },+ optionalArgs: () => ({ createdAt: 'now' }),+ unionThatImplementsInterface: ({ typename = '' }: { typename?: string }) => ({+ message: 'A message',+ ownProp1: 'Own prop 1',+ ownProp2: 'Own prop 2',+ __typename: typename || 'ClientErrorNameInvalid',+ }),+ someScalarValue: () => 'someScalarValue',+ repository: () => ({ createdAt: 'now' }),+ account: () => ({ __typename: 'User', ...johnUser }),+ coordinates: () => ({ __typename: 'Bank', x: '1', y: '2', address: '3' }),+};++const executeOperation = async (+ operation: GraphqlOperation,+): Promise<ExecutionResult> =>+ await graphql({+ schema: executableSchema,+ source: operation.query,+ variableValues: operation.variables,+ rootValue: queryRootValue,+ });++const executableFetch = vi.fn(+ async (_url: RequestInfo | URL, requestInit?: RequestInit) => {+ const body = JSON.parse(String(requestInit?.body)) as+ | GraphqlOperation+ | GraphqlOperation[];++ const payload = Array.isArray(body)+ ? await Promise.all(body.map(executeOperation))+ : await executeOperation(body);++ return new Response(JSON.stringify(payload), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ });+ },+) as unknown as typeof globalThis.fetch;++const URL_PLACEHOLDER = 'http://executable-schema.test/graphql';++describe('execute queries', () => {+ const client = createClient({+ url: URL_PLACEHOLDER,+ headers: () => ({ Auth: 'xxx' }),+ fetch: executableFetch,+ });++ it('first query', async () => {+ const res = await client.query({+ repository: {+ __args: {+ name: 'genql',+ },+ createdAt: true,+ },+ optionalArgs: {+ createdAt: true,+ },+ });+ expect(res.repository.createdAt).toBeTruthy();+ expect(res.optionalArgs.createdAt).toBeTruthy();+ });++ it('simple', async () => {+ const res = await client.query({+ user: {+ name: true,+ },+ });+ expect(res.user).toEqual(johnUser);+ });++ it('__typename is not optional', async () => {+ const res = await client.query({+ user: {+ name: true,+ __typename: true,+ },+ });+ expectTypeOf(res.user!.__typename).toEqualTypeOf<'User'>();+ expect(res.user?.__typename).toBe('User');+ });++ it('scalar value with argument', async () => {+ const withoutArgs = await client.query({+ someScalarValue: true,+ });+ expect(withoutArgs.someScalarValue?.toLocaleLowerCase).toBeTruthy();++ const withArgs = await client.query({+ someScalarValue: { __args: { x: 1 } },+ });+ expect(withArgs.someScalarValue?.toLocaleLowerCase).toBeTruthy();+ });++ it('falsy values are not fetched', async () => {+ const res = await client.query({+ coordinates: {+ x: false,+ y: true,+ },+ });+ expect(res.coordinates?.x).toBeUndefined();+ expect(res.coordinates?.y).toBeDefined();+ });++ it('required field and nested fields', async () => {+ const res = await client.query({+ repository: {+ __args: {+ name: 'genql',+ owner: 'remorses',+ },+ ...everything,+ forks: {+ __args: { filter: 'test' },+ edges: { node: { name: true, number: true } },+ },+ },+ });+ // @ts-expect-error top level fields are filtered based on the query+ void res?.account;+ // no optional chaining because repository is non null+ expectTypeOf(res.repository.createdAt).toEqualTypeOf<string>();+ expectTypeOf(res.repository.__typename).toEqualTypeOf<'Repository'>();+ expectTypeOf(+ res.repository?.forks?.edges?.map((edge) => edge?.node?.name),+ ).toEqualTypeOf<(string | undefined)[] | undefined>();+ expectTypeOf(+ res.repository?.forks?.edges?.map((edge) => edge?.node?.number),+ ).toEqualTypeOf<(number | undefined)[] | undefined>();+ expect(res.repository.createdAt).toBeTruthy();+ });++ it('union types only 1 on_ normal syntax', async () => {+ const { account } = await client.query({+ account: {+ __typename: 1,+ on_User: {+ name: 1,+ },+ },+ });+ // @ts-expect-error on_User should be removed from the response type+ void account?.on_User;+ expect(account?.__typename).toBeTruthy();+ expectTypeOf(account).toExtend<Account | undefined>();+ expectTypeOf(account?.__typename).toEqualTypeOf<+ 'User' | 'Guest' | undefined+ >();+ });++ it('ability to query interfaces that a union implements', async () => {+ const { unionThatImplementsInterface } = await client.query({+ unionThatImplementsInterface: {+ __typename: 1,+ on_ClientErrorNameInvalid: {+ message: 1,+ ownProp2: 1,+ },+ on_ClientError: {+ message: 1,+ },+ on_ClientErrorWithoutInterface: {+ ownProp3: 1,+ },+ },+ });++ if (unionThatImplementsInterface?.__typename === 'ClientErrorNameInvalid') {+ expect(unionThatImplementsInterface?.ownProp2).toBeTruthy();+ }+ if (+ unionThatImplementsInterface?.__typename === 'ClientErrorWithoutInterface'+ ) {+ expect(unionThatImplementsInterface?.ownProp3).toBeTruthy();+ }+ expect(unionThatImplementsInterface?.__typename).toBe(+ 'ClientErrorNameInvalid',+ );+ });++ it('interface types normal syntax', async () => {+ const res = await client.query({+ coordinates: {+ x: 1,+ __typename: 1,+ on_Bank: {+ address: 1,+ },+ },+ });+ const coordinates = res.coordinates;+ expectTypeOf(coordinates?.x).toEqualTypeOf<string | undefined>();+ if (coordinates && 'address' in coordinates) {+ expectTypeOf(coordinates?.address).toEqualTypeOf<string | undefined>();+ expect(coordinates?.address).toBeTruthy();+ }+ // common types are accessible without guards+ expect(coordinates?.x).toBeTruthy();+ expect(coordinates?.__typename).toBeTruthy();+ });++ it('multiple interfaces types normal syntax', async () => {+ const { coordinates } = await client.query({+ coordinates: {+ __typename: 1,+ on_Bank: {+ address: 1,+ x: 1,+ },+ on_House: {+ y: 1,+ x: 1,+ owner: {+ name: 1,+ },+ },+ },+ });++ expectTypeOf(coordinates?.x).toEqualTypeOf<string | undefined>();+ expectTypeOf(coordinates).toExtend<Point | undefined>();+ expectTypeOf(coordinates?.__typename).toEqualTypeOf<+ 'Bank' | 'House' | undefined+ >();+ expect(coordinates?.x).toBeTruthy();+ expect(coordinates?.__typename).toBeTruthy();+ if (coordinates && 'address' in coordinates) {+ void coordinates?.address;+ void coordinates?.x;+ } else if (isHouse(coordinates)) {+ void coordinates?.owner;+ void coordinates?.x;+ void coordinates?.y;+ }+ });++ it('errors', async () => {+ const err = await client+ .query({+ throwsError: true,+ })+ .catch((error) => error);+ expect(err).toBeInstanceOf(Error);+ expect(err).toBeInstanceOf(GenqlError);+ expect((err as GenqlError).errors.length).toBeTruthy();+ });++ it('errors are thrown with batching', async () => {+ const batchingClient = createClient({+ url: URL_PLACEHOLDER,+ fetch: executableFetch,+ batch: {+ batchInterval: 100,+ },+ });+ const [err1, err2] = await Promise.all([+ batchingClient+ .query({+ throwsError: true,+ })+ .catch((error) => error),+ batchingClient+ .query({+ throwsError: true,+ })+ .catch((error) => error),+ ]);+ expect(err1).toBeInstanceOf(GenqlError);+ expect(err2).toBeInstanceOf(GenqlError);+ expect((err1 as GenqlError).errors.length).toBeTruthy();+ expect((err2 as GenqlError).errors.length).toBeTruthy();+ });++ it('1 error and 1 result with batching', async () => {+ const batchingClient = createClient({+ url: URL_PLACEHOLDER,+ fetch: executableFetch,+ batch: {+ batchInterval: 100,+ },+ });+ const [err1, res] = await Promise.all([+ batchingClient+ .query({+ throwsError: true,+ })+ .catch((error) => error),+ batchingClient.query({+ user: {+ name: true,+ },+ }),+ ]);+ expect(err1).toBeInstanceOf(GenqlError);+ expect((err1 as GenqlError).errors.length).toBeTruthy();+ expect(res.user).toEqual(johnUser);+ });++ it('batches requests', async () => {+ let batchedQueryLength = -1;+ let requestsCount = 0;+ const batchingClient = createClient({+ batch: true,+ fetcher: async (body) => {+ requestsCount += 1;+ batchedQueryLength = Array.isArray(body) ? body.length : -1;+ const payload = Array.isArray(body)+ ? await Promise.all(body.map(executeOperation))+ : await executeOperation(body);++ // the real transport JSON-serializes; mirror it so GraphQLError+ // instances become the plain objects a fetcher returns+ return JSON.parse(JSON.stringify(payload));+ },+ });+ const res = await Promise.all([+ batchingClient.query({+ coordinates: {+ __typename: 1,+ x: 1,+ },+ }),+ batchingClient.query({+ coordinates: {+ __typename: 1,+ y: 1,+ },+ }),+ ]);+ expect(res.length).toBe(2);+ expect(batchedQueryLength).toBe(2);+ expect(requestsCount).toBe(1);+ });++ it('headers function gets called every time', async () => {+ let headersCalledNTimes = 0;+ const countingClient = createClient({+ url: URL_PLACEHOLDER,+ fetch: executableFetch,+ headers: () => {+ headersCalledNTimes++;+ return {};+ },+ });++ await countingClient.query({+ coordinates: {+ __typename: 1,+ x: 1,+ },+ });+ await countingClient.query({+ coordinates: {+ __typename: 1,+ y: 1,+ },+ });++ expect(headersCalledNTimes).toBe(2);+ });++ it('async headers function gets called every time', async () => {+ let headersCalledNTimes = 0;+ const countingClient = createClient({+ url: URL_PLACEHOLDER,+ fetch: executableFetch,+ headers: async () => {+ headersCalledNTimes++;+ return {};+ },+ });++ await countingClient.query({+ coordinates: {+ __typename: 1,+ x: 1,+ },+ });+ await countingClient.query({+ coordinates: {+ __typename: 1,+ y: 1,+ },+ });++ expect(headersCalledNTimes).toBe(2);+ });+});++// upstream asserted `DeepPartial<User>` assignability for the mock; keep the+// equivalent compile-time check without the tsdef dependency.+expectTypeOf(johnUser).toExtend<Partial<User>>();diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/index.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/index.tsnew file mode 100644index 00000000000..f6d80adc71f--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/index.ts@@ -0,0 +1,65 @@+// @ts-nocheck+import type {+ QueryGenqlSelection,+ Query,+ SubscriptionGenqlSelection,+ Subscription,+} from './schema'+import {+ linkTypeMap,+ createClient as createClientOriginal,+ generateGraphqlOperation,+ type FieldsSelection,+ type GraphqlOperation,+ type ClientOptions,+ GenqlError,+} from './runtime'+export type { FieldsSelection } from './runtime'+export { GenqlError }++import types from './types'+export * from './schema'+const typeMap = linkTypeMap(types as any)++export interface Client {+ query<R extends QueryGenqlSelection>(+ request: R & { __name?: string },+ ): Promise<FieldsSelection<Query, R>>+}++export const createClient = function (options?: ClientOptions): Client {+ return createClientOriginal({+ url: undefined,++ ...options,+ queryRoot: typeMap.Query!,+ mutationRoot: typeMap.Mutation!,+ subscriptionRoot: typeMap.Subscription!,+ }) as any+}++export const everything = {+ __scalar: true,+}++export type QueryResult<fields extends QueryGenqlSelection> = FieldsSelection<+ Query,+ fields+>+export const generateQueryOp: (+ fields: QueryGenqlSelection & { __name?: string },+) => GraphqlOperation = function (fields) {+ return generateGraphqlOperation('query', typeMap.Query!, fields as any)+}++export type SubscriptionResult<fields extends SubscriptionGenqlSelection> =+ FieldsSelection<Subscription, fields>+export const generateSubscriptionOp: (+ fields: SubscriptionGenqlSelection & { __name?: string },+) => GraphqlOperation = function (fields) {+ return generateGraphqlOperation(+ 'subscription',+ typeMap.Subscription!,+ fields as any,+ )+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/batcher.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/batcher.tsnew file mode 100644index 00000000000..eedcda3fbc9--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/batcher.ts@@ -0,0 +1,271 @@+// @ts-nocheck+import type { GraphqlOperation } from './generateGraphqlOperation'+import { GenqlError } from './error'++type Variables = Record<string, any>++type QueryError = Error & {+ message: string++ locations?: Array<{+ line: number+ column: number+ }>+ path?: any+ rid: string+ details?: Record<string, any>+}+type Result = {+ data: Record<string, any>+ errors: Array<QueryError>+}+type Fetcher = (+ batchedQuery: GraphqlOperation | Array<GraphqlOperation>,+) => Promise<Array<Result>>+type Options = {+ batchInterval?: number+ shouldBatch?: boolean+ maxBatchSize?: number+}+type Queue = Array<{+ request: GraphqlOperation+ resolve: (...args: Array<any>) => any+ reject: (...args: Array<any>) => any+}>++/**+ * takes a list of requests (queue) and batches them into a single server request.+ * It will then resolve each individual requests promise with the appropriate data.+ * @private+ * @param {QueryBatcher} client - the client to use+ * @param {Queue} queue - the list of requests to batch+ */+function dispatchQueueBatch(client: QueryBatcher, queue: Queue): void {+ let batchedQuery: any = queue.map((item) => item.request)++ if (batchedQuery.length === 1) {+ batchedQuery = batchedQuery[0]+ }++ client.fetcher(batchedQuery).then((responses: any) => {+ if (queue.length === 1 && !Array.isArray(responses)) {+ if (responses.errors && responses.errors.length) {+ queue[0].reject(+ new GenqlError(responses.errors, responses.data),+ )+ return+ }++ queue[0].resolve(responses)+ return+ } else if (responses.length !== queue.length) {+ throw new Error('response length did not match query length')+ }++ for (let i = 0; i < queue.length; i++) {+ if (responses[i].errors && responses[i].errors.length) {+ queue[i].reject(+ new GenqlError(responses[i].errors, responses[i].data),+ )+ } else {+ queue[i].resolve(responses[i])+ }+ }+ }).catch((error: any) => {+ // Reject every queued request if the batched fetch fails (e.g. network+ // error), otherwise callers hang forever and the rejection is unhandled.+ for (const item of queue) {+ item.reject(error)+ }+ })+}++/**+ * creates a list of requests to batch according to max batch size.+ * @private+ * @param {QueryBatcher} client - the client to create list of requests from from+ * @param {Options} options - the options for the batch+ */+function dispatchQueue(client: QueryBatcher, options: Options): void {+ const queue = client._queue+ const maxBatchSize = options.maxBatchSize || 0+ client._queue = []++ if (maxBatchSize > 0 && maxBatchSize < queue.length) {+ for (let i = 0; i < queue.length / maxBatchSize; i++) {+ dispatchQueueBatch(+ client,+ queue.slice(i * maxBatchSize, (i + 1) * maxBatchSize),+ )+ }+ } else {+ dispatchQueueBatch(client, queue)+ }+}+/**+ * Create a batcher client.+ * @param {Fetcher} fetcher - A function that can handle the network requests to graphql endpoint+ * @param {Options} options - the options to be used by client+ * @param {boolean} options.shouldBatch - should the client batch requests. (default true)+ * @param {integer} options.batchInterval - duration (in MS) of each batch window. (default 6)+ * @param {integer} options.maxBatchSize - max number of requests in a batch. (default 0)+ * @param {boolean} options.defaultHeaders - default headers to include with every request+ *+ * @example+ * const fetcher = batchedQuery => fetch('path/to/graphql', {+ * method: 'post',+ * headers: {+ * Accept: 'application/json',+ * 'Content-Type': 'application/json',+ * },+ * body: JSON.stringify(batchedQuery),+ * credentials: 'include',+ * })+ * .then(response => response.json())+ *+ * const client = new QueryBatcher(fetcher, { maxBatchSize: 10 })+ */++export class QueryBatcher {+ fetcher: Fetcher+ _options: Options+ _queue: Queue++ constructor(+ fetcher: Fetcher,+ {+ batchInterval = 6,+ shouldBatch = true,+ maxBatchSize = 0,+ }: Options = {},+ ) {+ this.fetcher = fetcher+ this._options = {+ batchInterval,+ shouldBatch,+ maxBatchSize,+ }+ this._queue = []+ }++ /**+ * Fetch will send a graphql request and return the parsed json.+ * @param {string} query - the graphql query.+ * @param {Variables} variables - any variables you wish to inject as key/value pairs.+ * @param {[string]} operationName - the graphql operationName.+ * @param {Options} overrides - the client options overrides.+ *+ * @return {promise} resolves to parsed json of server response+ *+ * @example+ * client.fetch(`+ * query getHuman($id: ID!) {+ * human(id: $id) {+ * name+ * height+ * }+ * }+ * `, { id: "1001" }, 'getHuman')+ * .then(human => {+ * // do something with human+ * console.log(human);+ * });+ */+ fetch(+ query: string,+ variables?: Variables,+ operationName?: string,+ overrides: Options = {},+ ): Promise<Result> {+ const request: GraphqlOperation = {+ query,+ }+ const options = Object.assign({}, this._options, overrides)++ if (variables) {+ request.variables = variables+ }++ if (operationName) {+ request.operationName = operationName+ }++ const promise = new Promise<Result>((resolve, reject) => {+ this._queue.push({+ request,+ resolve,+ reject,+ })++ if (this._queue.length === 1) {+ if (options.shouldBatch) {+ setTimeout(+ () => dispatchQueue(this, options),+ options.batchInterval,+ )+ } else {+ dispatchQueue(this, options)+ }+ }+ })+ return promise+ }++ /**+ * Fetch will send a graphql request and return the parsed json.+ * @param {string} query - the graphql query.+ * @param {Variables} variables - any variables you wish to inject as key/value pairs.+ * @param {[string]} operationName - the graphql operationName.+ * @param {Options} overrides - the client options overrides.+ *+ * @return {Promise<Array<Result>>} resolves to parsed json of server response+ *+ * @example+ * client.forceFetch(`+ * query getHuman($id: ID!) {+ * human(id: $id) {+ * name+ * height+ * }+ * }+ * `, { id: "1001" }, 'getHuman')+ * .then(human => {+ * // do something with human+ * console.log(human);+ * });+ */+ forceFetch(+ query: string,+ variables?: Variables,+ operationName?: string,+ overrides: Options = {},+ ): Promise<Result> {+ const request: GraphqlOperation = {+ query,+ }+ const options = Object.assign({}, this._options, overrides, {+ shouldBatch: false,+ })++ if (variables) {+ request.variables = variables+ }++ if (operationName) {+ request.operationName = operationName+ }++ const promise = new Promise<Result>((resolve, reject) => {+ const client = new QueryBatcher(this.fetcher, this._options)+ client._queue = [+ {+ request,+ resolve,+ reject,+ },+ ]+ dispatchQueue(client, options)+ })+ return promise+ }+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/createClient.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/createClient.tsnew file mode 100644index 00000000000..755617ed7ae--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/createClient.ts@@ -0,0 +1,68 @@+// @ts-nocheck++import { type BatchOptions, createFetcher } from './fetcher'+import type { ExecutionResult, LinkedType } from './types'+import {+ generateGraphqlOperation,+ type GraphqlOperation,+} from './generateGraphqlOperation'++export type Headers =+ | HeadersInit+ | (() => HeadersInit)+ | (() => Promise<HeadersInit>)++export type BaseFetcher = (+ operation: GraphqlOperation | GraphqlOperation[],+) => Promise<ExecutionResult | ExecutionResult[]>++export type ClientOptions = Omit<RequestInit, 'body' | 'headers'> & {+ url?: string+ batch?: BatchOptions | boolean+ fetcher?: BaseFetcher+ fetch?: Function+ headers?: Headers+}++export const createClient = ({+ queryRoot,+ mutationRoot,+ subscriptionRoot,+ ...options+}: ClientOptions & {+ queryRoot?: LinkedType+ mutationRoot?: LinkedType+ subscriptionRoot?: LinkedType+}) => {+ const fetcher = createFetcher(options)+ const client: {+ query?: Function+ mutation?: Function+ } = {}++ if (queryRoot) {+ client.query = (request: any) => {+ if (!queryRoot) throw new Error('queryRoot argument is missing')++ const resultPromise = fetcher(+ generateGraphqlOperation('query', queryRoot, request),+ )++ return resultPromise+ }+ }+ if (mutationRoot) {+ client.mutation = (request: any) => {+ if (!mutationRoot)+ throw new Error('mutationRoot argument is missing')++ const resultPromise = fetcher(+ generateGraphqlOperation('mutation', mutationRoot, request),+ )++ return resultPromise+ }+ }++ return client as any+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/error.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/error.tsnew file mode 100644index 00000000000..d9039ebe0c3--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/error.ts@@ -0,0 +1,29 @@+// @ts-nocheck+export class GenqlError extends Error {+ errors: Array<GraphqlError> = []+ /**+ * Partial data returned by the server+ */+ data?: any+ constructor(errors: any[], data: any) {+ let message = Array.isArray(errors)+ ? errors.map((x) => x?.message || '').join('\n')+ : ''+ if (!message) {+ message = 'GraphQL error'+ }+ super(message)+ this.errors = errors+ this.data = data+ }+}++interface GraphqlError {+ message: string+ locations?: Array<{+ line: number+ column: number+ }>+ path?: string[]+ extensions?: Record<string, any>+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/fetcher.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/fetcher.tsnew file mode 100644index 00000000000..78c98ffbdcc--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/fetcher.ts@@ -0,0 +1,98 @@+// @ts-nocheck+import { QueryBatcher } from './batcher'++import type { ClientOptions } from './createClient'+import type { GraphqlOperation } from './generateGraphqlOperation'+import { GenqlError } from './error'++export interface Fetcher {+ (gql: GraphqlOperation): Promise<any>+}++export type BatchOptions = {+ batchInterval?: number // ms+ maxBatchSize?: number+}++const DEFAULT_BATCH_OPTIONS = {+ maxBatchSize: 10,+ batchInterval: 40,+}++export const createFetcher = ({+ url,+ headers = {},+ fetcher,+ fetch: _fetch,+ batch = false,+ ...rest+}: ClientOptions): Fetcher => {+ if (!url && !fetcher) {+ throw new Error('url or fetcher is required')+ }+ if (!fetcher) {+ fetcher = async (body) => {+ let headersObject =+ typeof headers == 'function' ? await headers() : headers+ headersObject = headersObject || {}+ if (typeof fetch === 'undefined' && !_fetch) {+ throw new Error(+ 'Global `fetch` function is not available, pass a fetch polyfill to Genql `createClient`',+ )+ }+ let fetchImpl = _fetch || fetch+ const res = await fetchImpl(url!, {+ headers: {+ 'Content-Type': 'application/json',+ ...headersObject,+ },+ method: 'POST',+ body: JSON.stringify(body),+ ...rest,+ })+ if (!res.ok) {+ throw new Error(`${res.statusText}: ${await res.text()}`)+ }+ const json = await res.json()+ return json+ }+ }++ if (!batch) {+ return async (body) => {+ const json = await fetcher!(body)+ if (Array.isArray(json)) {+ return json.map((json) => {+ if (json?.errors?.length) {+ throw new GenqlError(json.errors || [], json.data)+ }+ return json.data+ })+ } else {+ if (json?.errors?.length) {+ throw new GenqlError(json.errors || [], json.data)+ }+ return json.data+ }+ }+ }++ const batcher = new QueryBatcher(+ async (batchedQuery) => {+ // console.log(batchedQuery) // [{ query: 'query{user{age}}', variables: {} }, ...]+ const json = await fetcher!(batchedQuery)+ return json as any+ },+ batch === true ? DEFAULT_BATCH_OPTIONS : batch,+ )++ return async ({ query, variables }) => {+ const json = await batcher.fetch(query, variables)+ if (json?.data) {+ return json.data+ }+ throw new Error(+ 'Genql batch fetcher returned unexpected result ' + JSON.stringify(json),+ )+ }+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/generateGraphqlOperation.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/generateGraphqlOperation.tsnew file mode 100644index 00000000000..c618019ec82--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/generateGraphqlOperation.ts@@ -0,0 +1,225 @@+// @ts-nocheck+import type { LinkedField, LinkedType } from './types'++export interface Args {+ [arg: string]: any | undefined+}++export interface Fields {+ [field: string]: Request+}++export type Request = boolean | number | Fields++export interface Variables {+ [name: string]: {+ value: any+ typing: [LinkedType, string]+ }+}++export interface Context {+ root: LinkedType+ varCounter: number+ variables: Variables+ fragmentCounter: number+ fragments: string[]+}++export interface GraphqlOperation {+ query: string+ variables?: { [name: string]: any }+ operationName?: string+}++const parseRequest = (+ request: Request | undefined,+ ctx: Context,+ path: string[],+): string => {+ if (typeof request === 'object' && '__args' in request) {+ const args: any = request.__args+ let fields: Request | undefined = { ...request }+ delete fields.__args+ const argNames = Object.keys(args)++ if (argNames.length === 0) {+ return parseRequest(fields, ctx, path)+ }++ const field = getFieldFromPath(ctx.root, path)++ const argStrings = argNames.map((argName) => {+ ctx.varCounter+++ const varName = `v${ctx.varCounter}`++ const typing = field.args && field.args[argName] // typeMap used here, .args++ if (!typing) {+ throw new Error(+ `no typing defined for argument \`${argName}\` in path \`${path.join(+ '.',+ )}\``,+ )+ }++ ctx.variables[varName] = {+ value: args[argName],+ typing,+ }++ return `${argName}:$${varName}`+ })+ return `(${argStrings})${parseRequest(fields, ctx, path)}`+ } else if (typeof request === 'object' && Object.keys(request).length > 0) {+ const fields = request+ const fieldNames = Object.keys(fields).filter((k) => Boolean(fields[k]))++ if (fieldNames.length === 0) {+ throw new Error(+ `field selection should not be empty: ${path.join('.')}`,+ )+ }++ const type =+ path.length > 0 ? getFieldFromPath(ctx.root, path).type : ctx.root+ const scalarFields = type.scalar++ let scalarFieldsFragment: string | undefined++ if (fieldNames.includes('__scalar')) {+ const falsyFieldNames = new Set(+ Object.keys(fields).filter((k) => !Boolean(fields[k])),+ )+ if (scalarFields?.length) {+ ctx.fragmentCounter+++ scalarFieldsFragment = `f${ctx.fragmentCounter}`++ ctx.fragments.push(+ `fragment ${scalarFieldsFragment} on ${+ type.name+ }{${scalarFields+ .filter((f) => !falsyFieldNames.has(f))+ .join(',')}}`,+ )+ }+ }++ const fieldsSelection = fieldNames+ .filter((f) => !['__scalar', '__name'].includes(f))+ .map((f) => {+ const parsed = parseRequest(fields[f], ctx, [...path, f])++ if (f.startsWith('on_')) {+ ctx.fragmentCounter+++ const implementationFragment = `f${ctx.fragmentCounter}`++ const typeMatch = f.match(/^on_(.+)/)++ if (!typeMatch || !typeMatch[1])+ throw new Error('match failed')++ ctx.fragments.push(+ `fragment ${implementationFragment} on ${typeMatch[1]}${parsed}`,+ )++ return `...${implementationFragment}`+ } else {+ return `${f}${parsed}`+ }+ })+ .concat(scalarFieldsFragment ? [`...${scalarFieldsFragment}`] : [])+ .join(',')++ return `{${fieldsSelection}}`+ } else {+ return ''+ }+}++export const generateGraphqlOperation = (+ operation: 'query' | 'mutation' | 'subscription',+ root: LinkedType,+ fields?: Fields,+): GraphqlOperation => {+ const ctx: Context = {+ root: root,+ varCounter: 0,+ variables: {},+ fragmentCounter: 0,+ fragments: [],+ }+ const result = parseRequest(fields, ctx, [])++ const varNames = Object.keys(ctx.variables)++ const varsString =+ varNames.length > 0+ ? `(${varNames.map((v) => {+ const variableType = ctx.variables[v].typing[1]+ return `$${v}:${variableType}`+ })})`+ : ''++ const operationName = fields?.__name || ''++ return {+ query: [+ `${operation} ${operationName}${varsString}${result}`,+ ...ctx.fragments,+ ].join(','),+ variables: Object.keys(ctx.variables).reduce<{ [name: string]: any }>(+ (r, v) => {+ r[v] = ctx.variables[v].value+ return r+ },+ {},+ ),+ ...(operationName ? { operationName: operationName.toString() } : {}),+ }+}++export const getFieldFromPath = (+ root: LinkedType | undefined,+ path: string[],+) => {+ let current: LinkedField | undefined++ if (!root) throw new Error('root type is not provided')++ if (path.length === 0) throw new Error(`path is empty`)++ path.forEach((f) => {+ const type = current ? current.type : root++ if (!type.fields)+ throw new Error(`type \`${type.name}\` does not have fields`)++ const possibleTypes = Object.keys(type.fields)+ .filter((i) => i.startsWith('on_'))+ .reduce(+ (types, fieldName) => {+ const field = type.fields && type.fields[fieldName]+ if (field) types.push(field.type)+ return types+ },+ [type],+ )++ let field: LinkedField | null = null++ possibleTypes.forEach((type) => {+ const found = type.fields && type.fields[f]+ if (found) field = found+ })++ if (!field)+ throw new Error(+ `type \`${type.name}\` does not have a field \`${f}\``,+ )++ current = field+ })++ return current as LinkedField+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/index.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/index.tsnew file mode 100644index 00000000000..130ed4bf792--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/index.ts@@ -0,0 +1,13 @@+// @ts-nocheck+export { createClient } from './createClient'+export type { ClientOptions } from './createClient'+export type { FieldsSelection } from './typeSelection'+export { generateGraphqlOperation } from './generateGraphqlOperation'+export type { GraphqlOperation } from './generateGraphqlOperation'+export { linkTypeMap } from './linkTypeMap'+// export { Observable } from 'zen-observable-ts'+export { createFetcher } from './fetcher'+export { GenqlError } from './error'+export const everything = {+ __scalar: true,+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/linkTypeMap.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/linkTypeMap.tsnew file mode 100644index 00000000000..117da16bb72--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/linkTypeMap.ts@@ -0,0 +1,139 @@+// @ts-nocheck+import type {+ CompressedType,+ CompressedTypeMap,+ LinkedArgMap,+ LinkedField,+ LinkedType,+ LinkedTypeMap,+} from './types'++export interface PartialLinkedFieldMap {+ [field: string]: {+ type: string+ args?: LinkedArgMap+ }+}++export const linkTypeMap = (+ typeMap: CompressedTypeMap<number>,+): LinkedTypeMap => {+ const indexToName: Record<number, string> = Object.assign(+ {},+ ...Object.keys(typeMap.types).map((k, i) => ({ [i]: k })),+ )++ let intermediaryTypeMap = Object.assign(+ {},+ ...Object.keys(typeMap.types || {}).map(+ (k): Record<string, LinkedType> => {+ const type: CompressedType = typeMap.types[k]!+ const fields = type || {}+ return {+ [k]: {+ name: k,+ // type scalar properties+ scalar: Object.keys(fields).filter((f) => {+ const [type] = fields[f] || []+ return type && typeMap.scalars.includes(type)+ }),+ // fields with corresponding `type` and `args`+ fields: Object.assign(+ {},+ ...Object.keys(fields).map(+ (f): PartialLinkedFieldMap => {+ const [typeIndex, args] = fields[f] || []+ if (typeIndex == null) {+ return {}+ }+ return {+ [f]: {+ // replace index with type name+ type: indexToName[typeIndex],+ args: Object.assign(+ {},+ ...Object.keys(args || {}).map(+ (k) => {+ // if argTypeString == argTypeName, argTypeString is missing, need to readd it+ if (!args || !args[k]) {+ return+ }+ const [+ argTypeName,+ argTypeString,+ ] = args[k] as any+ return {+ [k]: [+ indexToName[+ argTypeName+ ],+ argTypeString ||+ indexToName[+ argTypeName+ ],+ ],+ }+ },+ ),+ ),+ },+ }+ },+ ),+ ),+ },+ }+ },+ ),+ )+ const res = resolveConcreteTypes(intermediaryTypeMap)+ return res+}++// replace typename with concrete type+export const resolveConcreteTypes = (linkedTypeMap: LinkedTypeMap) => {+ Object.keys(linkedTypeMap).forEach((typeNameFromKey) => {+ const type: LinkedType = linkedTypeMap[typeNameFromKey]!+ // type.name = typeNameFromKey+ if (!type.fields) {+ return+ }++ const fields = type.fields++ Object.keys(fields).forEach((f) => {+ const field: LinkedField = fields[f]!++ if (field.args) {+ const args = field.args+ Object.keys(args).forEach((key) => {+ const arg = args[key]++ if (arg) {+ const [typeName] = arg++ if (typeof typeName === 'string') {+ if (!linkedTypeMap[typeName]) {+ linkedTypeMap[typeName] = { name: typeName }+ }++ arg[0] = linkedTypeMap[typeName]!+ }+ }+ })+ }++ const typeName = field.type as LinkedType | string++ if (typeof typeName === 'string') {+ if (!linkedTypeMap[typeName]) {+ linkedTypeMap[typeName] = { name: typeName }+ }++ field.type = linkedTypeMap[typeName]!+ }+ })+ })++ return linkedTypeMap+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/typeSelection.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/typeSelection.tsnew file mode 100644index 00000000000..ddca88d78be--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/typeSelection.ts@@ -0,0 +1,98 @@+// @ts-nocheck+//////////////////////////////////////////////////++// SOME THINGS TO KNOW BEFORE DIVING IN+/*+0. DST is the request type, SRC is the response type++1. FieldsSelection uses an object because currently is impossible to make recursive types++2. FieldsSelection is a recursive type that makes a type based on request type and fields++3. HandleObject handles object types++4. Handle__scalar adds all scalar properties excluding non scalar props+*/++export type FieldsSelection<SRC extends Anify<DST> | undefined, DST> = {+ scalar: SRC+ union: Handle__isUnion<SRC, DST>+ object: HandleObject<SRC, DST>+ array: SRC extends Nil+ ? never+ : SRC extends (infer T)[]+ ? Array<FieldsSelection<T, DST>>+ : never+ __scalar: Handle__scalar<SRC, DST>+ never: never+}[DST extends Nil+ ? 'never'+ : SRC extends Nil+ ? 'never'+ : DST extends false | 0+ ? 'never'+ : SRC extends Scalar+ ? 'scalar'+ : SRC extends any[]+ ? 'array'+ : SRC extends { __isUnion?: any }+ ? 'union'+ : DST extends { __scalar?: any }+ ? '__scalar'+ : DST extends {}+ ? 'object'+ : 'never']++type HandleObject<SRC extends Anify<DST>, DST> = SRC extends Nil+ ? never+ : Pick<+ {+ // using keyof SRC to maintain ?: relations of SRC type+ [Key in keyof SRC]: Key extends keyof DST+ ? FieldsSelection<+ NonNullable<SRC[Key]>,+ NonNullable<DST[Key]>+ >+ : SRC[Key]+ },+ Exclude<keyof DST, FieldsToRemove>+ // {+ // // remove falsy values+ // [Key in keyof DST]: DST[Key] extends false | 0 ? never : Key+ // }[keyof DST]+ >++type Handle__scalar<SRC extends Anify<DST>, DST> = SRC extends Nil+ ? never+ : Pick<+ // continue processing fields that are in DST, directly pass SRC type if not in DST+ {+ [Key in keyof SRC]: Key extends keyof DST+ ? FieldsSelection<SRC[Key], DST[Key]>+ : SRC[Key]+ },+ // remove fields that are not scalars or are not in DST+ {+ [Key in keyof SRC]: SRC[Key] extends Nil+ ? never+ : Key extends FieldsToRemove+ ? never+ : SRC[Key] extends Scalar+ ? Key+ : Key extends keyof DST+ ? Key+ : never+ }[keyof SRC]+ >++type Handle__isUnion<SRC extends Anify<DST>, DST> = SRC extends Nil+ ? never+ : Omit<SRC, FieldsToRemove> // just return the union type++type Scalar = string | number | Date | boolean | null | undefined++type Anify<T> = { [P in keyof T]?: any }++type FieldsToRemove = '__isUnion' | '__scalar' | '__name' | '__args'++type Nil = undefined | nulldiff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/types.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/types.tsnew file mode 100644index 00000000000..3f0bc30b9e8--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/runtime/types.ts@@ -0,0 +1,69 @@+// @ts-nocheck++export interface ExecutionResult<TData = { [key: string]: any }> {+ errors?: Array<Error>+ data?: TData | null+}++export interface ArgMap<keyType = number> {+ [arg: string]: [keyType, string] | [keyType] | undefined+}++export type CompressedField<keyType = number> = [+ type: keyType,+ args?: ArgMap<keyType>,+]++export interface CompressedFieldMap<keyType = number> {+ [field: string]: CompressedField<keyType> | undefined+}++export type CompressedType<keyType = number> = CompressedFieldMap<keyType>++export interface CompressedTypeMap<keyType = number> {+ scalars: Array<keyType>+ types: {+ [type: string]: CompressedType<keyType> | undefined+ }+}++// normal types+export type Field<keyType = number> = {+ type: keyType+ args?: ArgMap<keyType>+}++export interface FieldMap<keyType = number> {+ [field: string]: Field<keyType> | undefined+}++export type Type<keyType = number> = FieldMap<keyType>++export interface TypeMap<keyType = number> {+ scalars: Array<keyType>+ types: {+ [type: string]: Type<keyType> | undefined+ }+}++export interface LinkedArgMap {+ [arg: string]: [LinkedType, string] | undefined+}+export interface LinkedField {+ type: LinkedType+ args?: LinkedArgMap+}++export interface LinkedFieldMap {+ [field: string]: LinkedField | undefined+}++export interface LinkedType {+ name: string+ fields?: LinkedFieldMap+ scalar?: string[]+}++export interface LinkedTypeMap {+ [type: string]: LinkedType | undefined+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.graphql b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.graphqlnew file mode 100644index 00000000000..7d5917a3079--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.graphql@@ -0,0 +1,110 @@+enum SomeEnum {+ X+ Y+ Z+}++enum SomeEnum2 {+ hello+ world+}++type Query {+ """Some description"""+ repository(name: String!, owner: String): Repository!+ optionalArgs(name: String, owner: String): Repository!+ user: User+ someScalarValue(x: Float): String+ recursiveType(requiredVal: [String!]): [RecursiveType]+ throwsError: String!+ account: Account+ coordinates: Point+ unionThatImplementsInterface(typename: String): GenericError+ InterfaceNotImplemented: InterfaceNotImplemented+}++type RecursiveType {+ value: String+ recurse(arg: Int): RecursiveType+}++type Repository {+ createdAt: String!+ forks(filter: String): ForkConnection+}++type ForkConnection {+ edges: [ForkEdge]+}++type ForkEdge {+ cursor: String+ node: Fork+}++type Fork {+ name: String+ number: Int+}++type User {+ """Some description"""+ name: String+ common: Int+}++type Subscription {+ user: User+}++union Account = User | Guest++type Guest {+ anonymous: Boolean+ common: Int+}++type House implements Point {+ owner: User+ x: String+ y: String+}++type Bank implements Point {+ address: String+ x: String+ y: String+}++interface Point {+ x: String+ y: String+}++interface ClientError {+ message: String!+}++type ClientErrorNameAlreadyTaken implements ClientError {+ message: String!+ ownProp1: String+}++type ClientErrorNameInvalid implements ClientError {+ message: String!+ ownProp2: String+}++type ClientErrorWithoutInterface {+ ownProp3: String+}++union GenericError = ClientErrorNameAlreadyTaken | ClientErrorNameInvalid | ClientErrorWithoutInterface++interface InterfaceNotImplemented {+ id: ID!+ title: String+ url: String+ permalink: String+ entry_id: ID+}\ No newline at end of filediff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.tsnew file mode 100644index 00000000000..a0b5a44cfce--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/schema.ts@@ -0,0 +1,433 @@+// @ts-nocheck+export type Scalars = {+ String: string,+ Float: number,+ Int: number,+ Boolean: boolean,+ ID: string,+}++export type SomeEnum = 'X' | 'Y' | 'Z'++export type SomeEnum2 = 'hello' | 'world'++export interface Query {+ /** Some description */+ repository: Repository+ optionalArgs: Repository+ user?: User+ someScalarValue?: Scalars['String']+ recursiveType?: (RecursiveType | undefined)[]+ throwsError: Scalars['String']+ account?: Account+ coordinates?: Point+ unionThatImplementsInterface?: GenericError+ InterfaceNotImplemented?: InterfaceNotImplemented+ __typename: 'Query'+}++export interface RecursiveType {+ value?: Scalars['String']+ recurse?: RecursiveType+ __typename: 'RecursiveType'+}++export interface Repository {+ createdAt: Scalars['String']+ forks?: ForkConnection+ __typename: 'Repository'+}++export interface ForkConnection {+ edges?: (ForkEdge | undefined)[]+ __typename: 'ForkConnection'+}++export interface ForkEdge {+ cursor?: Scalars['String']+ node?: Fork+ __typename: 'ForkEdge'+}++export interface Fork {+ name?: Scalars['String']+ number?: Scalars['Int']+ __typename: 'Fork'+}++export interface User {+ /** Some description */+ name?: Scalars['String']+ common?: Scalars['Int']+ __typename: 'User'+}++export interface Subscription {+ user?: User+ __typename: 'Subscription'+}++export type Account = (User | Guest) & { __isUnion?: true }++export interface Guest {+ anonymous?: Scalars['Boolean']+ common?: Scalars['Int']+ __typename: 'Guest'+}++export interface House {+ owner?: User+ x?: Scalars['String']+ y?: Scalars['String']+ __typename: 'House'+}++export interface Bank {+ address?: Scalars['String']+ x?: Scalars['String']+ y?: Scalars['String']+ __typename: 'Bank'+}++export type Point = (House | Bank) & { __isUnion?: true }++export type ClientError = (ClientErrorNameAlreadyTaken | ClientErrorNameInvalid) & { __isUnion?: true }++export interface ClientErrorNameAlreadyTaken {+ message: Scalars['String']+ ownProp1?: Scalars['String']+ __typename: 'ClientErrorNameAlreadyTaken'+}++export interface ClientErrorNameInvalid {+ message: Scalars['String']+ ownProp2?: Scalars['String']+ __typename: 'ClientErrorNameInvalid'+}++export interface ClientErrorWithoutInterface {+ ownProp3?: Scalars['String']+ __typename: 'ClientErrorWithoutInterface'+}++export type GenericError = (ClientErrorNameAlreadyTaken | ClientErrorNameInvalid | ClientErrorWithoutInterface) & { __isUnion?: true }++export interface InterfaceNotImplemented {+ id: Scalars['ID']+ title?: Scalars['String']+ url?: Scalars['String']+ permalink?: Scalars['String']+ entry_id?: Scalars['ID']+ __typename: string+}++export interface QueryGenqlSelection{+ /** Some description */+ repository?: (RepositoryGenqlSelection & { __args: {name: Scalars['String'], owner?: (Scalars['String'] | null)} })+ optionalArgs?: (RepositoryGenqlSelection & { __args?: {name?: (Scalars['String'] | null), owner?: (Scalars['String'] | null)} })+ user?: UserGenqlSelection+ someScalarValue?: { __args: {x?: (Scalars['Float'] | null)} } | boolean | number+ recursiveType?: (RecursiveTypeGenqlSelection & { __args?: {requiredVal?: (Scalars['String'][] | null)} })+ throwsError?: boolean | number+ account?: AccountGenqlSelection+ coordinates?: PointGenqlSelection+ unionThatImplementsInterface?: (GenericErrorGenqlSelection & { __args?: {typename?: (Scalars['String'] | null)} })+ InterfaceNotImplemented?: InterfaceNotImplementedGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface RecursiveTypeGenqlSelection{+ value?: boolean | number+ recurse?: (RecursiveTypeGenqlSelection & { __args?: {arg?: (Scalars['Int'] | null)} })+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface RepositoryGenqlSelection{+ createdAt?: boolean | number+ forks?: (ForkConnectionGenqlSelection & { __args?: {filter?: (Scalars['String'] | null)} })+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ForkConnectionGenqlSelection{+ edges?: ForkEdgeGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ForkEdgeGenqlSelection{+ cursor?: boolean | number+ node?: ForkGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ForkGenqlSelection{+ name?: boolean | number+ number?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface UserGenqlSelection{+ /** Some description */+ name?: boolean | number+ common?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface SubscriptionGenqlSelection{+ user?: UserGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface AccountGenqlSelection{+ on_User?:UserGenqlSelection,+ on_Guest?:GuestGenqlSelection,+ __typename?: boolean | number+}++export interface GuestGenqlSelection{+ anonymous?: boolean | number+ common?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface HouseGenqlSelection{+ owner?: UserGenqlSelection+ x?: boolean | number+ y?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface BankGenqlSelection{+ address?: boolean | number+ x?: boolean | number+ y?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface PointGenqlSelection{+ x?: boolean | number+ y?: boolean | number+ on_House?: HouseGenqlSelection+ on_Bank?: BankGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ClientErrorGenqlSelection{+ message?: boolean | number+ on_ClientErrorNameAlreadyTaken?: ClientErrorNameAlreadyTakenGenqlSelection+ on_ClientErrorNameInvalid?: ClientErrorNameInvalidGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ClientErrorNameAlreadyTakenGenqlSelection{+ message?: boolean | number+ ownProp1?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ClientErrorNameInvalidGenqlSelection{+ message?: boolean | number+ ownProp2?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface ClientErrorWithoutInterfaceGenqlSelection{+ ownProp3?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface GenericErrorGenqlSelection{+ on_ClientErrorNameAlreadyTaken?:ClientErrorNameAlreadyTakenGenqlSelection,+ on_ClientErrorNameInvalid?:ClientErrorNameInvalidGenqlSelection,+ on_ClientErrorWithoutInterface?:ClientErrorWithoutInterfaceGenqlSelection,+ on_ClientError?: ClientErrorGenqlSelection,+ __typename?: boolean | number+}++export interface InterfaceNotImplementedGenqlSelection{+ id?: boolean | number+ title?: boolean | number+ url?: boolean | number+ permalink?: boolean | number+ entry_id?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}+++ const Query_possibleTypes: string[] = ['Query']+ export const isQuery = (obj?: { __typename?: any } | null): obj is Query => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isQuery"')+ return Query_possibleTypes.includes(obj.__typename)+ }++++ const RecursiveType_possibleTypes: string[] = ['RecursiveType']+ export const isRecursiveType = (obj?: { __typename?: any } | null): obj is RecursiveType => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isRecursiveType"')+ return RecursiveType_possibleTypes.includes(obj.__typename)+ }++++ const Repository_possibleTypes: string[] = ['Repository']+ export const isRepository = (obj?: { __typename?: any } | null): obj is Repository => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isRepository"')+ return Repository_possibleTypes.includes(obj.__typename)+ }++++ const ForkConnection_possibleTypes: string[] = ['ForkConnection']+ export const isForkConnection = (obj?: { __typename?: any } | null): obj is ForkConnection => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isForkConnection"')+ return ForkConnection_possibleTypes.includes(obj.__typename)+ }++++ const ForkEdge_possibleTypes: string[] = ['ForkEdge']+ export const isForkEdge = (obj?: { __typename?: any } | null): obj is ForkEdge => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isForkEdge"')+ return ForkEdge_possibleTypes.includes(obj.__typename)+ }++++ const Fork_possibleTypes: string[] = ['Fork']+ export const isFork = (obj?: { __typename?: any } | null): obj is Fork => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isFork"')+ return Fork_possibleTypes.includes(obj.__typename)+ }++++ const User_possibleTypes: string[] = ['User']+ export const isUser = (obj?: { __typename?: any } | null): obj is User => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isUser"')+ return User_possibleTypes.includes(obj.__typename)+ }++++ const Subscription_possibleTypes: string[] = ['Subscription']+ export const isSubscription = (obj?: { __typename?: any } | null): obj is Subscription => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isSubscription"')+ return Subscription_possibleTypes.includes(obj.__typename)+ }++++ const Account_possibleTypes: string[] = ['User','Guest']+ export const isAccount = (obj?: { __typename?: any } | null): obj is Account => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isAccount"')+ return Account_possibleTypes.includes(obj.__typename)+ }++++ const Guest_possibleTypes: string[] = ['Guest']+ export const isGuest = (obj?: { __typename?: any } | null): obj is Guest => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isGuest"')+ return Guest_possibleTypes.includes(obj.__typename)+ }++++ const House_possibleTypes: string[] = ['House']+ export const isHouse = (obj?: { __typename?: any } | null): obj is House => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isHouse"')+ return House_possibleTypes.includes(obj.__typename)+ }++++ const Bank_possibleTypes: string[] = ['Bank']+ export const isBank = (obj?: { __typename?: any } | null): obj is Bank => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isBank"')+ return Bank_possibleTypes.includes(obj.__typename)+ }++++ const Point_possibleTypes: string[] = ['House','Bank']+ export const isPoint = (obj?: { __typename?: any } | null): obj is Point => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isPoint"')+ return Point_possibleTypes.includes(obj.__typename)+ }++++ const ClientError_possibleTypes: string[] = ['ClientErrorNameAlreadyTaken','ClientErrorNameInvalid']+ export const isClientError = (obj?: { __typename?: any } | null): obj is ClientError => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isClientError"')+ return ClientError_possibleTypes.includes(obj.__typename)+ }++++ const ClientErrorNameAlreadyTaken_possibleTypes: string[] = ['ClientErrorNameAlreadyTaken']+ export const isClientErrorNameAlreadyTaken = (obj?: { __typename?: any } | null): obj is ClientErrorNameAlreadyTaken => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isClientErrorNameAlreadyTaken"')+ return ClientErrorNameAlreadyTaken_possibleTypes.includes(obj.__typename)+ }++++ const ClientErrorNameInvalid_possibleTypes: string[] = ['ClientErrorNameInvalid']+ export const isClientErrorNameInvalid = (obj?: { __typename?: any } | null): obj is ClientErrorNameInvalid => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isClientErrorNameInvalid"')+ return ClientErrorNameInvalid_possibleTypes.includes(obj.__typename)+ }++++ const ClientErrorWithoutInterface_possibleTypes: string[] = ['ClientErrorWithoutInterface']+ export const isClientErrorWithoutInterface = (obj?: { __typename?: any } | null): obj is ClientErrorWithoutInterface => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isClientErrorWithoutInterface"')+ return ClientErrorWithoutInterface_possibleTypes.includes(obj.__typename)+ }++++ const GenericError_possibleTypes: string[] = ['ClientErrorNameAlreadyTaken','ClientErrorNameInvalid','ClientErrorWithoutInterface']+ export const isGenericError = (obj?: { __typename?: any } | null): obj is GenericError => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isGenericError"')+ return GenericError_possibleTypes.includes(obj.__typename)+ }++++ const InterfaceNotImplemented_possibleTypes: string[] = []+ export const isInterfaceNotImplemented = (obj?: { __typename?: any } | null): obj is InterfaceNotImplemented => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isInterfaceNotImplemented"')+ return InterfaceNotImplemented_possibleTypes.includes(obj.__typename)+ }+++export const enumSomeEnum = {+ X: 'X' as const,+ Y: 'Y' as const,+ Z: 'Z' as const+}++export const enumSomeEnum2 = {+ hello: 'hello' as const,+ world: 'world' as const+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/types.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/types.tsnew file mode 100644index 00000000000..089b456e66e--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/generated/types.ts@@ -0,0 +1,317 @@+export default {+ "scalars": [+ 0,+ 1,+ 3,+ 4,+ 6,+ 15,+ 25+ ],+ "types": {+ "SomeEnum": {},+ "SomeEnum2": {},+ "Query": {+ "repository": [+ 7,+ {+ "name": [+ 3,+ "String!"+ ],+ "owner": [+ 3+ ]+ }+ ],+ "optionalArgs": [+ 7,+ {+ "name": [+ 3+ ],+ "owner": [+ 3+ ]+ }+ ],+ "user": [+ 11+ ],+ "someScalarValue": [+ 3,+ {+ "x": [+ 4+ ]+ }+ ],+ "recursiveType": [+ 5,+ {+ "requiredVal": [+ 3,+ "[String!]"+ ]+ }+ ],+ "throwsError": [+ 3+ ],+ "account": [+ 13+ ],+ "coordinates": [+ 18+ ],+ "unionThatImplementsInterface": [+ 23,+ {+ "typename": [+ 3+ ]+ }+ ],+ "InterfaceNotImplemented": [+ 24+ ],+ "__typename": [+ 3+ ]+ },+ "String": {},+ "Float": {},+ "RecursiveType": {+ "value": [+ 3+ ],+ "recurse": [+ 5,+ {+ "arg": [+ 6+ ]+ }+ ],+ "__typename": [+ 3+ ]+ },+ "Int": {},+ "Repository": {+ "createdAt": [+ 3+ ],+ "forks": [+ 8,+ {+ "filter": [+ 3+ ]+ }+ ],+ "__typename": [+ 3+ ]+ },+ "ForkConnection": {+ "edges": [+ 9+ ],+ "__typename": [+ 3+ ]+ },+ "ForkEdge": {+ "cursor": [+ 3+ ],+ "node": [+ 10+ ],+ "__typename": [+ 3+ ]+ },+ "Fork": {+ "name": [+ 3+ ],+ "number": [+ 6+ ],+ "__typename": [+ 3+ ]+ },+ "User": {+ "name": [+ 3+ ],+ "common": [+ 6+ ],+ "__typename": [+ 3+ ]+ },+ "Subscription": {+ "user": [+ 11+ ],+ "__typename": [+ 3+ ]+ },+ "Account": {+ "on_User": [+ 11+ ],+ "on_Guest": [+ 14+ ],+ "__typename": [+ 3+ ]+ },+ "Guest": {+ "anonymous": [+ 15+ ],+ "common": [+ 6+ ],+ "__typename": [+ 3+ ]+ },+ "Boolean": {},+ "House": {+ "owner": [+ 11+ ],+ "x": [+ 3+ ],+ "y": [+ 3+ ],+ "__typename": [+ 3+ ]+ },+ "Bank": {+ "address": [+ 3+ ],+ "x": [+ 3+ ],+ "y": [+ 3+ ],+ "__typename": [+ 3+ ]+ },+ "Point": {+ "x": [+ 3+ ],+ "y": [+ 3+ ],+ "on_House": [+ 16+ ],+ "on_Bank": [+ 17+ ],+ "__typename": [+ 3+ ]+ },+ "ClientError": {+ "message": [+ 3+ ],+ "on_ClientErrorNameAlreadyTaken": [+ 20+ ],+ "on_ClientErrorNameInvalid": [+ 21+ ],+ "__typename": [+ 3+ ]+ },+ "ClientErrorNameAlreadyTaken": {+ "message": [+ 3+ ],+ "ownProp1": [+ 3+ ],+ "__typename": [+ 3+ ]+ },+ "ClientErrorNameInvalid": {+ "message": [+ 3+ ],+ "ownProp2": [+ 3+ ],+ "__typename": [+ 3+ ]+ },+ "ClientErrorWithoutInterface": {+ "ownProp3": [+ 3+ ],+ "__typename": [+ 3+ ]+ },+ "GenericError": {+ "on_ClientErrorNameAlreadyTaken": [+ 20+ ],+ "on_ClientErrorNameInvalid": [+ 21+ ],+ "on_ClientErrorWithoutInterface": [+ 22+ ],+ "on_ClientError": [+ 19+ ],+ "__typename": [+ 3+ ]+ },+ "InterfaceNotImplemented": {+ "id": [+ 25+ ],+ "title": [+ 3+ ],+ "url": [+ 3+ ],+ "permalink": [+ 3+ ],+ "entry_id": [+ 25+ ],+ "__typename": [+ 3+ ]+ },+ "ID": {}+ }+}\ No newline at end of filediff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/schema.graphql b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/schema.graphqlnew file mode 100644index 00000000000..7399f127656--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/fixture/schema.graphql@@ -0,0 +1,134 @@+enum SomeEnum {+ X+ Y+ Z+}+enum SomeEnum2 {+ hello+ world+}++# Some comment+type Query {+ """+ Some description+ """+ repository(name: String!, owner: String): Repository!+ optionalArgs(name: String, owner: String): Repository!+ user: User+ someScalarValue(x: Float): String+ recursiveType(requiredVal: [String!]): [RecursiveType]+ throwsError: String!+}++type RecursiveType {+ value: String+ recurse(arg: Int): RecursiveType+}++type Repository {+ createdAt: String!+ forks(filter: String): ForkConnection+}++type ForkConnection {+ edges: [ForkEdge]+}++type ForkEdge {+ cursor: String+ node: Fork+}++type Fork {+ name: String+ number: Int+}++type User {+ """+ Some description+ """+ name: String+ common: Int+}++# ---++type Subscription {+ user: User+}++##################++extend type Query {+ account: Account+}++union Account = User | Guest++type Guest {+ anonymous: Boolean+ common: Int+}++##################++extend type Query {+ coordinates: Point+}++type House implements Point {+ owner: User+ x: String+ y: String+}++type Bank implements Point {+ address: String+ x: String+ y: String+}++interface Point {+ x: String+ y: String+}++# Ability to query interfaces that a union implements https://github.com/remorses/genql/issues/44++interface ClientError {+ message: String!+}++type ClientErrorNameAlreadyTaken implements ClientError {+ message: String!+ ownProp1: String+}++type ClientErrorNameInvalid implements ClientError {+ message: String!+ ownProp2: String+}++type ClientErrorWithoutInterface {+ ownProp3: String+}++union GenericError =+ | ClientErrorNameAlreadyTaken+ | ClientErrorNameInvalid+ | ClientErrorWithoutInterface++extend type Query {+ unionThatImplementsInterface(typename: String): GenericError+ InterfaceNotImplemented: InterfaceNotImplemented+}++interface InterfaceNotImplemented {+ id: ID!+ title: String+ url: String+ permalink: String+ entry_id: ID+}diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generate-queries.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generate-queries.test.tsnew file mode 100644index 00000000000..16bab0f837d--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generate-queries.test.ts@@ -0,0 +1,175 @@+import { describe, expect, expectTypeOf, it } from 'vitest';++import { prettify } from '../../genql/helpers/prettify';+import {+ enumSomeEnum,+ everything,+ generateQueryOp,+ generateSubscriptionOp,+} from './fixture/generated';++// Port of remorses/[email protected] integration-tests/tests/simple.ts ("generate+// queries") onto vitest: mocha `describe/it` and snap-shot-it snapshots become+// vitest snapshots, tsd's `expectType` becomes `expectTypeOf`. The selections+// and test names are upstream's, unchanged.+describe('generate queries', () => {+ it('enum string is present', () => {+ expectTypeOf(enumSomeEnum.X).toEqualTypeOf<'X'>();+ expect(enumSomeEnum.X).toBe('X');+ expect(enumSomeEnum.Y).toBe('Y');+ });++ it('query', async () => {+ const { query } = generateQueryOp({+ repository: {+ __args: {+ name: 'repo',+ owner: 'owner',+ },+ createdAt: true,+ forks: {+ edges: {+ cursor: true,+ node: {+ ...everything,+ },+ },+ },+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('optional arg', async () => {+ const { query } = generateQueryOp({+ optionalArgs: {+ createdAt: true,+ forks: {+ edges: {+ cursor: true,+ node: {+ ...everything,+ },+ },+ },+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('recursive type', async () => {+ const { query } = generateQueryOp({+ recursiveType: {+ value: 1,+ recurse: {+ ...everything,+ recurse: {+ value: 1,+ recurse: {+ ...everything,+ recurse: {+ ...everything,+ },+ },+ },+ },+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('recursive type with args', async () => {+ const { query } = generateQueryOp({+ recursiveType: {+ __args: { requiredVal: ['ciao'] },+ value: 1,+ recurse: {+ __args: {+ arg: 1,+ },+ ...everything,+ recurse: {+ __args: {+ arg: 1,+ },+ value: 1,+ recurse: {+ __args: {+ arg: 1,+ },+ ...everything,+ recurse: {+ ...everything,+ },+ },+ },+ },+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('use __name operation name', async () => {+ const NAME = 'SomeName';+ const { query } = generateSubscriptionOp({+ __name: NAME,+ user: {+ __scalar: true,+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('subscriptions', async () => {+ const { query } = generateSubscriptionOp({+ user: {+ __scalar: true,+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('many', async () => {+ const { query } = generateQueryOp({+ repository: {+ __args: {+ name: 'repo',+ owner: 'owner',+ },+ createdAt: true,+ forks: {+ edges: {+ cursor: true,+ node: {+ ...everything,+ },+ },+ },+ },+ user: {+ ...everything,+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('do not fetch falsy fields', async () => {+ const { query } = generateSubscriptionOp({+ user: {+ common: false,+ name: true,+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });++ it('do not fetch falsy fields with __scalar', async () => {+ const { query } = generateSubscriptionOp({+ user: {+ common: false,+ __scalar: true,+ },+ });+ expect(await prettify(query, 'graphql')).toMatchSnapshot();+ });+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generated-fixture-drift.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generated-fixture-drift.test.tsnew file mode 100644index 00000000000..08c5d8623a8--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/generated-fixture-drift.test.ts@@ -0,0 +1,83 @@+import { readFileSync } from 'node:fs';+import { cp, mkdtemp, readdir, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { generate } from '../../genql';++// The checked-in client under fixture/generated is the vendored genql engine's+// output for upstream's own integration-test schema (fixture/schema.graphql,+// verbatim from remorses/[email protected] integration-tests/). Checking it in lets+// the ported upstream tests import it statically, so their tsd-style type+// assertions are verified by the package typecheck. This test regenerates the+// client and compares byte-for-byte so the fixture can never drift from what+// the engine actually produces.+//+// To refresh after an intentional engine change:+// UPDATE_GENQL_UPSTREAM_FIXTURE=1 npx vitest run src/generate/__tests__/upstream-3.0.5/generated-fixture-drift.test.ts+const FIXTURE_DIR = join(+ dirname(fileURLToPath(import.meta.url)),+ 'fixture',+ 'generated',+);++const SCHEMA_PATH = join(+ dirname(fileURLToPath(import.meta.url)),+ 'fixture',+ 'schema.graphql',+);++const listFilesRecursively = async (root: string): Promise<string[]> => {+ const entries = await readdir(root, { recursive: true, withFileTypes: true });++ return entries+ .filter((entry) => entry.isFile())+ .map((entry) => relative(root, join(entry.parentPath, entry.name)))+ .sort();+};++describe('upstream fixture client matches the engine output', () => {+ let temporaryDir: string;+ let regeneratedDir: string;++ beforeAll(async () => {+ temporaryDir = await mkdtemp(join(tmpdir(), 'twenty-genql-fixture-'));+ regeneratedDir = join(temporaryDir, 'generated');++ await generate({+ schema: readFileSync(SCHEMA_PATH, 'utf-8'),+ output: regeneratedDir,+ });++ if (+ ['1', 'true'].includes(process.env.UPDATE_GENQL_UPSTREAM_FIXTURE ?? '')+ ) {+ await rm(FIXTURE_DIR, { recursive: true, force: true });+ await cp(regeneratedDir, FIXTURE_DIR, { recursive: true });+ }+ }, 60000);++ afterAll(async () => {+ if (temporaryDir) {+ await rm(temporaryDir, { recursive: true, force: true });+ }+ });++ it('produces the same file list', async () => {+ expect(await listFilesRecursively(regeneratedDir)).toEqual(+ await listFilesRecursively(FIXTURE_DIR),+ );+ });++ it('produces byte-identical file contents', async () => {+ for (const file of await listFilesRecursively(FIXTURE_DIR)) {+ const regenerated = await readFile(join(regeneratedDir, file), 'utf-8');+ const checkedIn = await readFile(join(FIXTURE_DIR, file), 'utf-8');++ expect(regenerated, `fixture/generated/${file} is stale`).toBe(checkedIn);+ }+ });+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-context.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-context.test.tsnew file mode 100644index 00000000000..d0dafa8a59c--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-context.test.ts@@ -0,0 +1,23 @@+import { describe, expect, test } from 'vitest';++import { prettify } from '../../genql/helpers/prettify';+import { RenderContext } from '../../genql/render/common/RenderContext';++// Port of remorses/[email protected]+// cli/src/render/common/__tests__/RenderContext.test.ts; `toCode` and+// `prettify` are awaited since the prettier 3 migration made them async.+describe('RenderContext', () => {+ test('prettify', async () => {+ const renderContext = new RenderContext();+ renderContext.addCodeBlock('interface A{}');+ expect(await renderContext.toCode('typescript', true)).toBe(+ await prettify('interface A{}', 'typescript'),+ );+ });++ test('raw', async () => {+ const renderContext = new RenderContext();+ renderContext.addCodeBlock('raw string');+ expect(await renderContext.toCode()).toBe('raw string');+ });+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-schema.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-schema.test.tsnew file mode 100644index 00000000000..9a95e4d04da--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-schema.test.ts@@ -0,0 +1,46 @@+import { expect, test } from 'vitest';++import { prettify } from '../../genql/helpers/prettify';+import { renderSchema } from '../../genql/render/schema/renderSchema';+import { schemaRenderTest } from './render-test-helpers';++// Port of remorses/[email protected] cli/src/render/schema/renderSchema.test.ts;+// `prettify` is awaited since the prettier 3 migration made it async.+test('renderSchema', async () => {+ expect(+ await schemaRenderTest(+ /* GraphQL */ `+ type A {+ some: String+ }++ type B {+ some: String @deprecated+ }++ type Query {+ _: Boolean+ }+ `,+ renderSchema,+ 'graphql',+ ),+ ).toBe(+ await prettify(+ /* GraphQL */ `+ type A {+ some: String+ }++ type B {+ some: String @deprecated+ }++ type Query {+ _: Boolean+ }+ `,+ 'graphql',+ ),+ );+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-test-helpers.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-test-helpers.tsnew file mode 100644index 00000000000..3a15dd9c9c5--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-test-helpers.ts@@ -0,0 +1,60 @@+import {+ buildClientSchema,+ buildSchema,+ getIntrospectionQuery,+ graphql,+ type GraphQLNamedType,+ type GraphQLSchema,+ type IntrospectionQuery,+} from 'graphql';+import { type BuiltInParserName } from 'prettier';++import { RenderContext } from '../../genql/render/common/RenderContext';++// Port of remorses/[email protected] cli/src/testHelpers/render.ts (minus the+// file-based typeRenderTestCase, which no ported test uses). `toCode` is+// awaited because the vendored prettify moved to prettier 3's async format.+export type TypeRenderer = (+ type: GraphQLNamedType,+ renderContext: RenderContext,+) => void;++export type SchemaRenderer = (+ schema: GraphQLSchema,+ renderContext: RenderContext,+) => void;++// Round-trips the SDL through introspection, as upstream did, so the+// renderers see a client schema exactly like one built from a real endpoint.+export const toClientSchema = async (+ schemaGql: string,+): Promise<GraphQLSchema> => {+ const schema = buildSchema(schemaGql);++ const introspectionResponse = await graphql({+ schema,+ source: getIntrospectionQuery(),+ });++ if (!introspectionResponse.data) {+ throw new Error(JSON.stringify(introspectionResponse.errors));+ }++ return buildClientSchema(+ introspectionResponse.data as unknown as IntrospectionQuery,+ );+};++export const schemaRenderTest = async (+ schemaGql: string,+ renderer: SchemaRenderer,+ parser?: BuiltInParserName,+): Promise<string> => {+ const schema = await toClientSchema(schemaGql);++ const renderContext = new RenderContext(schema);++ renderer(schema, renderContext);++ return await renderContext.toCode(parser, true);+};diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-typing.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-typing.test.tsnew file mode 100644index 00000000000..bf7f539390f--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/render-typing.test.ts@@ -0,0 +1,130 @@+import { type GraphQLObjectType, type GraphQLSchema } from 'graphql';+import { beforeAll, describe, expect, test } from 'vitest';++import { renderTyping } from '../../genql/render/common/renderTyping';+import { toClientSchema } from './render-test-helpers';++// Port of remorses/[email protected]+// cli/src/render/common/__tests__/renderTyping.test.ts, unchanged apart from+// the vitest imports.+let schema: GraphQLSchema;++const testCase = (+ field: string,+ expected: string,+ undefinableValues: boolean,+ undefinableFields: boolean,+) => {+ const fields = (schema.getType('Object') as GraphQLObjectType).getFields();+ const actual = renderTyping(+ fields[field].type,+ undefinableValues,+ undefinableFields,+ );++ expect(actual).toBe(expected);+};++describe('renderTyping', () => {+ beforeAll(async () => {+ schema = await toClientSchema(/* GraphQL */ `+ type Object {+ value: Int!+ maybeValue: Int+ valueList: [Int!]!+ maybeValueList: [Int]!+ valueMaybeList: [Int!]+ maybeValueMaybeList: [Int]+ nested: [[[Int!]!]!]!+ maybeNested: [[[Int]]]+ }+ type Query {+ _: Boolean+ }+ `);+ });++ test('nullable', () => {+ testCase('value', ": Scalars['Int']", false, false);+ testCase('maybeValue', ": (Scalars['Int'] | null)", false, false);+ testCase('valueList', ": Scalars['Int'][]", false, false);+ testCase('maybeValueList', ": (Scalars['Int'] | null)[]", false, false);+ testCase('valueMaybeList', ": (Scalars['Int'][] | null)", false, false);+ testCase(+ 'maybeValueMaybeList',+ ": ((Scalars['Int'] | null)[] | null)",+ false,+ false,+ );+ testCase('nested', ": Scalars['Int'][][][]", false, false);+ testCase(+ 'maybeNested',+ ": ((((Scalars['Int'] | null)[] | null)[] | null)[] | null)",+ false,+ false,+ );+ });++ test('undefinable values', () => {+ testCase('value', ": Scalars['Int']", true, false);+ testCase('maybeValue', ": (Scalars['Int'] | undefined)", true, false);+ testCase('valueList', ": Scalars['Int'][]", true, false);+ testCase('maybeValueList', ": (Scalars['Int'] | undefined)[]", true, false);+ testCase('valueMaybeList', ": (Scalars['Int'][] | undefined)", true, false);+ testCase(+ 'maybeValueMaybeList',+ ": ((Scalars['Int'] | undefined)[] | undefined)",+ true,+ false,+ );+ testCase('nested', ": Scalars['Int'][][][]", true, false);+ testCase(+ 'maybeNested',+ ": ((((Scalars['Int'] | undefined)[] | undefined)[] | undefined)[] | undefined)",+ true,+ false,+ );+ });++ test('undefinable fields', () => {+ testCase('value', ": Scalars['Int']", false, true);+ testCase('maybeValue', "?: (Scalars['Int'] | null)", false, true);+ testCase('valueList', ": Scalars['Int'][]", false, true);+ testCase('maybeValueList', ": (Scalars['Int'] | null)[]", false, true);+ testCase('valueMaybeList', "?: (Scalars['Int'][] | null)", false, true);+ testCase(+ 'maybeValueMaybeList',+ "?: ((Scalars['Int'] | null)[] | null)",+ false,+ true,+ );+ testCase('nested', ": Scalars['Int'][][][]", false, true);+ testCase(+ 'maybeNested',+ "?: ((((Scalars['Int'] | null)[] | null)[] | null)[] | null)",+ false,+ true,+ );+ });++ test('undefinable fields and values', () => {+ testCase('value', ": Scalars['Int']", true, true);+ testCase('maybeValue', "?: Scalars['Int']", true, true);+ testCase('valueList', ": Scalars['Int'][]", true, true);+ testCase('maybeValueList', ": (Scalars['Int'] | undefined)[]", true, true);+ testCase('valueMaybeList', "?: Scalars['Int'][]", true, true);+ testCase(+ 'maybeValueMaybeList',+ "?: (Scalars['Int'] | undefined)[]",+ true,+ true,+ );+ testCase('nested', ": Scalars['Int'][][][]", true, true);+ testCase(+ 'maybeNested',+ "?: (((Scalars['Int'] | undefined)[] | undefined)[] | undefined)[]",+ true,+ true,+ );+ });+});diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-map.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-map.test.tsnew file mode 100644index 00000000000..1a730b70aaa--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-map.test.ts@@ -0,0 +1,173 @@+import { type GraphQLNamedType } from 'graphql';+import { expect, test } from 'vitest';++import { RenderContext } from '../../genql/render/common/RenderContext';+import { objectType } from '../../genql/render/typeMap/objectType';+import { scalarType } from '../../genql/render/typeMap/scalarType';+import { unionType } from '../../genql/render/typeMap/unionType';+import { type Type } from '../../genql/runtime/types';+import { toClientSchema } from './render-test-helpers';++// Port of remorses/[email protected] cli/src/render/typeMap/index.test.ts. Upstream+// ran these with `output = true`, which skipped the assertions (a leftover+// "TODO readd tests") and let its expected values go stale: an argument's+// entry is `[namedType]`, with the wrapped type string appended only when it+// differs (e.g. `['Int', '[[[Int]]]']`), not always `[namedType, namedType]`.+// This port runs the assertions enabled, with the expected values corrected+// to the engine's actual (and upstream 3.0.5's actual) output.+type Renderer = (+ type: GraphQLNamedType,+ renderContext: RenderContext,+) => Type<string>;++const testCase = async (+ schemaGql: string,+ renderer: Renderer,+ cases: { [type: string]: Type<string> },+) => {+ const schema = await toClientSchema(schemaGql);++ const renderContext = new RenderContext(schema);++ for (const typeName in cases) {+ const type = schema.getType(typeName);+ const expected = cases[typeName];++ if (!type) {+ throw new Error(`type ${typeName} is not defined in the schema`);+ }++ expect(renderer(type, renderContext), typeName).toEqual(expected);+ }+};++test('scalarType', () =>+ testCase(+ /* GraphQL */ `+ enum Enum {+ some+ other+ }++ scalar Scalar++ type Query {+ scalar: String+ customScalar: Scalar+ enum: Enum+ }+ `,+ scalarType as Renderer,+ {+ String: {},+ Scalar: {},+ Enum: {},+ },+ ));++test('objectType', () =>+ testCase(+ /* GraphQL */ `+ interface Interface {+ some: String+ }++ type ImplementorA implements Interface {+ some: String+ }++ type ImplementorB implements Interface {+ some: String+ }++ type Object {+ scalar: Int+ object: Object+ interface: Interface+ optionalArgScalar(arg: Int): Int+ optionalArgObject(arg: Int): Object+ optionalArgInterface(arg: Int): Interface+ nestedArg(a: [[[Int]]], b: [[[Int!]!]!]!): Boolean+ }++ type ObjectWithoutScalar {+ object: Object+ interface: Interface+ }++ type Query {+ _: Boolean+ }+ `,+ objectType as Renderer,+ {+ Object: {+ scalar: { type: 'Int' },+ object: { type: 'Object' },+ interface: { type: 'Interface' },+ optionalArgScalar: {+ type: 'Int',+ args: { arg: ['Int'] },+ },+ optionalArgObject: {+ type: 'Object',+ args: { arg: ['Int'] },+ },+ optionalArgInterface: {+ type: 'Interface',+ args: { arg: ['Int'] },+ },+ nestedArg: {+ type: 'Boolean',+ args: {+ a: ['Int', '[[[Int]]]'],+ b: ['Int', '[[[Int!]!]!]!'],+ },+ },+ __typename: { type: 'String' },+ },+ Interface: {+ some: { type: 'String' },+ on_ImplementorA: { type: 'ImplementorA' },+ on_ImplementorB: { type: 'ImplementorB' },+ __typename: { type: 'String' },+ },+ ObjectWithoutScalar: {+ __typename: { type: 'String' },+ interface: { type: 'Interface' },+ object: { type: 'Object' },+ },+ },+ ));++test('unionType', () =>+ testCase(+ /* GraphQL */ `+ type Some {+ field: Int+ }++ type Other {+ field: Int+ }++ type Another {+ field: Int+ }++ union Union = Some | Other | Another++ type Query {+ _: Boolean+ }+ `,+ unionType as Renderer,+ {+ Union: {+ on_Some: { type: 'Some' },+ on_Other: { type: 'Other' },+ on_Another: { type: 'Another' },+ __typename: { type: 'String' },+ },+ },+ ));diff --git a/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-selection.test.ts b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-selection.test.tsnew file mode 100644index 00000000000..89c0dbda5a5--- /dev/null+++ b/packages/twenty-client-sdk/src/generate/__tests__/upstream-3.0.5/type-selection.test.ts@@ -0,0 +1,466 @@+import { describe, test } from 'vitest';++import { type FieldsSelection } from '../../genql/runtime/typeSelection';++// Port of remorses/[email protected] cli/src/typeSelection.test.ts, the type-level+// contract of the runtime's FieldsSelection. Every test body is compile-time+// only (dontExecute); the assertions are the `@ts-expect-error` comments,+// enforced by the package typecheck. Upstream's fully commented-out blocks+// ("hide fields in request", the trailing union experiments) are not ported.+type SRC = {+ literalsUnion: 'a' | 'b';+ nullableField: null | { x: boolean; optional?: string };+ list: {+ x: number;+ a: string;+ optional?: string;+ }[];+ nested?: {+ list?: {+ edges?: {+ x?: number;+ }[];+ }[];+ };+ category: {+ a: Date;+ b: Date;+ c: Date;+ nested1: {+ a: string;+ b: string;+ c: string;+ };+ nested2: {+ a: string;+ b: string;+ };+ optionalFieldsNested?: {+ a?: string;+ b?: number;+ };+ };+ optionalFields: {+ a?: string;+ b?: number;+ };+ order: {+ customer: {+ address: {+ city: 1;+ a: 1;+ b: 1;+ };+ };+ };+ union:+ | { a: string; __isUnion?: true }+ | { a: string; b: string; __isUnion?: true };+ nesting: {+ nestedUnion:+ | { a: string; __isUnion?: true }+ | { a: string; b: string; __isUnion?: true };+ };+ xxx: {+ xxx: boolean;+ };+ yyy: {+ yyy: boolean;+ };+ argumentSyntax: {+ a: string;+ optional?: string;+ nesting: {+ x: number;+ y: number;+ };+ union:+ | { a: string; __isUnion?: true }+ | { a: string; b: string; __isUnion?: true };+ list: {+ x: number;+ a: string;+ optional?: string;+ }[];+ };+ argumentScalar?: string;+};++describe('pick', () => {+ const req = {+ category: {+ a: 1,+ b: 1,+ nested1: {+ a: 1,+ },+ },+ argumentSyntax: {+ __args: { x: 3 },+ a: 1,+ nesting: {+ __scalar: 1,+ },+ },+ };+ const z: FieldsSelection<SRC, NoExtraProperties<typeof req>> = {} as any;+ test(+ 'response type picks from request type',+ dontExecute(() => {+ z.category;+ z.category.a;+ z.category.b;+ // @ts-expect-error c was not selected+ z.category.c;+ z.category.nested1.a;+ }),+ );+ test(+ 'response type does not have additional properties',+ dontExecute(() => {+ // @ts-expect-error not selected+ z.order;+ // @ts-expect-error not selected+ z.category.nested1.b;+ // @ts-expect-error not selected+ z.category.nested1.c;+ // @ts-expect-error not selected+ z.category.nested2;+ }),+ );+ test(+ 'argument syntax',+ dontExecute(() => {+ z.argumentSyntax.a.toLocaleLowerCase;+ }),+ );+});++describe('__scalar', () => {+ const req = {+ __name: 'name',+ category: {+ __scalar: 1,+ nested1: {+ a: 1,+ },+ },+ argumentSyntax: {+ __args: { a: 7 },+ __scalar: 1,+ },+ argumentScalar: {+ __args: { x: 9 },+ },+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'response type picks from request type',+ dontExecute(() => {+ z.category;+ z.category.a;+ z.category.b;+ z.category.c;+ z.category.nested1.a;+ z.category.a.getDate;+ z.category.b.getDate;+ }),+ );+ test(+ 'response type does not have additional properties',+ dontExecute(() => {+ // @ts-expect-error not selected+ z.order;+ // @ts-expect-error not selected+ z.category.nested1.b;+ // @ts-expect-error not selected+ z.category.nested1.c;+ // @ts-expect-error not selected+ z.category.nested2;+ }),+ );+ test(+ '__scalar is not present',+ dontExecute(() => {+ // @ts-expect-error __scalar is stripped from the response+ z.category.__scalar;+ }),+ );+ test(+ '__name is not present',+ dontExecute(() => {+ // @ts-expect-error __name is stripped from the response+ z.__name;+ }),+ );+ test(+ 'argument syntax',+ dontExecute(() => {+ z.argumentSyntax.a.toLocaleLowerCase;+ z.argumentSyntax.optional?.big;+ // @ts-expect-error nesting is not a scalar, __scalar does not select it+ z.argumentSyntax.nesting.x;+ }),+ );+ test(+ 'argument syntax on scalar',+ dontExecute(() => {+ z.argumentScalar;+ z.argumentScalar?.charAt;+ // @ts-expect-error not a string property+ z.argumentScalar.xx;+ }),+ );+});++describe('optional fields', () => {+ const req = {+ optionalFields: {+ a: 1,+ b: 1,+ },+ category: {+ optionalFieldsNested: {+ __scalar: 1,+ },+ },+ argumentSyntax: {+ optional: 1,+ },+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'optional fields are preserved',+ dontExecute(() => {+ // @ts-expect-error optional+ z.optionalFields.a.toLocaleLowerCase;+ z.optionalFields.a?.toLocaleLowerCase;+ // @ts-expect-error optional+ z.optionalFields.b.toLocaleLowerCase;+ z.optionalFields.b?.toFixed;+ // @ts-expect-error optional+ z.category.optionalFieldsNested.a;+ // @ts-expect-error optional+ z.category?.optionalFieldsNested.a;+ }),+ );+ test(+ 'optional fields are preserved in __scalar',+ dontExecute(() => {+ // @ts-expect-error optional+ z.optionalFields.a.toLocaleLowerCase;+ z.optionalFields.a?.toLocaleLowerCase;+ // @ts-expect-error optional+ z.optionalFields.b.toLocaleLowerCase;+ z.optionalFields.b?.toFixed;+ // @ts-expect-error optional+ z.category.optionalFieldsNested.a;+ z.category.optionalFieldsNested?.a?.toLocaleLowerCase;+ }),+ );+ test(+ 'argument syntax',+ dontExecute(() => {+ // @ts-expect-error optional+ z.argumentSyntax.optional.toLocaleLowerCase;+ z.argumentSyntax.optional?.toLocaleLowerCase;+ }),+ );+});++describe('unions', () => {+ const req = {+ union: {+ onX: {+ a: 1,+ __scalar: 1,+ },+ },+ nesting: {+ nestedUnion: {+ onX: {+ a: 1,+ },+ onY: {+ b: 1,+ },+ },+ },+ argumentSyntax: {+ union: {+ a: 1,+ onX: {+ b: 1,+ },+ },+ },+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'pick union fields',+ dontExecute(() => {+ z.union.a.toLocaleLowerCase;+ z.union.a.toLocaleLowerCase;+ z.nesting.nestedUnion.a.toLocaleLowerCase;+ }),+ );+ test(+ 'does not have __isUnion',+ dontExecute(() => {+ // @ts-expect-error __isUnion is stripped from the response+ z.union.__isUnion;+ // @ts-expect-error __isUnion is stripped from the response+ z.nesting.nestedUnion.__isUnion;+ }),+ );+ test(+ 'argument syntax',+ dontExecute(() => {+ z.argumentSyntax.union.a.charAt;+ // @ts-expect-error a was not selected on argumentSyntax+ z.argumentSyntax.a;+ }),+ );+});++describe('arrays', () => {+ const req = {+ list: {+ a: 1,+ x: 1,+ optional: 1,+ },+ nested: {+ __args: { x: 1 },+ __scalar: 1,+ list: {+ edges: {+ x: 1,+ },+ },+ },+ argumentSyntax: {+ list: {+ x: 1,+ optional: 1,+ },+ },+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'list',+ dontExecute(() => {+ z.list[0].a.charCodeAt;+ z.list[0].x.toFixed;+ }),+ );+ test(+ 'nested',+ dontExecute(() => {+ z.nested?.list?.[0]?.edges?.[0].x?.toFixed;+ }),+ );+ test(+ 'maintain optionals',+ dontExecute(() => {+ // @ts-expect-error optional+ z.list[0].optional.bold;+ z.list[0].optional?.bold;+ }),+ );+ test(+ 'args syntax',+ dontExecute(() => {+ z.argumentSyntax.list[0].x;+ z.argumentSyntax.list[0].optional?.charAt;+ // @ts-expect-error optional+ z.argumentSyntax.list[0].optional.charAt;+ }),+ );+});++describe('literals unions', () => {+ const req = {+ literalsUnion: 1,+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'literals',+ dontExecute(() => {+ z.literalsUnion.blink;+ z.literalsUnion === 'a';+ z.literalsUnion === 'b';+ // @ts-expect-error not a member of the literals union+ z.literalsUnion === 'x';+ }),+ );+});++describe('nullable fields', () => {+ const req = {+ nullableField: {+ x: 1,+ optional: 1,+ },+ };+ const z: FieldsSelection<SRC, typeof req> = {} as any;+ test(+ 'accessible',+ dontExecute(() => {+ z.nullableField.x;+ z.nullableField.optional?.big;+ // @ts-expect-error optional+ z.nullableField.optional.big;+ }),+ );+});++test(+ 'complex optional type with array',+ dontExecute(() => {+ interface ForkConnection {+ edges?: (ForkEdge | undefined)[];+ __typename?: 'ForkConnection';+ }++ interface ForkEdge {+ cursor?: string;+ node?: { x: string; y: string };+ nodes?: { x?: string; y?: string }[];+ __typename?: 'ForkEdge';+ }++ type X = FieldsSelection<+ ForkConnection | undefined,+ {+ edges?: {+ node: {+ x: 1;+ };+ nodes: {+ __scalar: 1;+ };+ };+ }+ >;+ const x: X = {} as any;+ x?.edges?.[0]?.node?.x?.toLocaleLowerCase;+ // @ts-expect-error y was not selected+ x?.edges?.[0]?.node?.y?.toLocaleLowerCase;+ x?.edges?.[0]?.nodes?.[0].x?.toLocaleLowerCase;+ x?.edges?.[0]?.nodes?.[0].y?.toLocaleLowerCase;+ }),+);++function dontExecute(_f: () => void) {+ return () => {};+}++type Impossible<TKeys extends keyof any> = {+ [TKey in TKeys]: never;+};++type NoExtraProperties<+ TObject,+ TExtended extends TObject = TObject,+> = TExtended & Impossible<Exclude<keyof TExtended, keyof TObject>>;diff --git a/packages/twenty-client-sdk/src/generate/genql/README.md b/packages/twenty-client-sdk/src/generate/genql/README.mdindex 55283dfb9dd..bb9e2f9ab90 100644--- a/packages/twenty-client-sdk/src/generate/genql/README.md+++ b/packages/twenty-client-sdk/src/generate/genql/README.md@@ -1,8 +1,14 @@# Vendored genql codegenThis folder is a narrowed, vendored copy of [`@genql/cli`](https://github.com/remorses/genql)-`3.0.5` (MIT, © Tommaso De Rossi "morse"), used to generate the typed GraphQL-client from an SDL string.+`3.0.5` (upstream commit `4a547db46a9a614cc2b5958e28674af351898464`; MIT,+© Tommaso De Rossi "morse"), used to generate the typed GraphQL client from an+SDL string.++Upstream's own test suite (integration + unit) is ported under+`../__tests__/upstream-3.0.5/` and pins the engine's behavior and generated+types; the snapshot tests (`../__tests__/genql-engine-output.test.ts` and the+ported suite's checked-in fixture client) pin its output byte-for-byte.It was vendored to remove `@genql/cli` from the dependency graph, which pulledin abandoned and vulnerable transitive packages (`undici`, `native-fetch`,@@ -12,7 +18,7 @@ in abandoned and vulnerable transitive packages (`undici`, `native-fetch`,- `render/` — the schema → TypeScript client renderers (copied verbatim).- `runtime/` — the genql client runtime, copied verbatim into every generated- client's `runtime/` folder (see `runtime-templates.ts`).+ client's `runtime/` folder (see `../runtime-templates.ts`).- `tasks/`, `helpers/`, `main.ts` — narrowed orchestration.## What was changed vs upstream@@ -26,7 +32,7 @@ in abandoned and vulnerable transitive packages (`undici`, `native-fetch`,- **Replaced `@graphql-tools/load`** with graphql's own `buildSchema` — Twentypasses an SDL string, so the extra loader (and its dependency) is unnecessary.Verified to produce byte-identical output.-- **Runtime files are imported as `?raw` text** (`runtime-templates.ts`) instead+- **Runtime files are imported as `?raw` text** (`../runtime-templates.ts`) insteadof read from `node_modules` at generation time, so they ship with this bundle.- **`Config` was narrowed** to the schema-string inputs Twenty actually passes(`schema`, `output`, `scalarTypes`, `sortProperties`). The introspectiondiff --git a/packages/twenty-client-sdk/src/generate/genql/tasks/clientTasks.ts b/packages/twenty-client-sdk/src/generate/genql/tasks/clientTasks.tsindex 1e73b8e359f..244394f0322 100644--- a/packages/twenty-client-sdk/src/generate/genql/tasks/clientTasks.ts+++ b/packages/twenty-client-sdk/src/generate/genql/tasks/clientTasks.ts@@ -11,7 +11,7 @@ import { renderResponseTypes } from '../render/responseTypes/renderResponseTypesimport { renderSchema } from '../render/schema/renderSchema';import { renderTypeGuards } from '../render/typeGuards/renderTypeGuards';import { renderTypeMap } from '../render/typeMap/renderTypeMap';-import { RUNTIME_TEMPLATE_FILES } from '../runtime-templates';+import { RUNTIME_TEMPLATE_FILES } from '../../runtime-templates';const schemaTypesFile = 'schema.ts';const schemaGqlFile = 'schema.graphql';diff --git a/packages/twenty-client-sdk/src/generate/genql/runtime-templates.ts b/packages/twenty-client-sdk/src/generate/runtime-templates.tssimilarity index 72%rename from packages/twenty-client-sdk/src/generate/genql/runtime-templates.tsrename to packages/twenty-client-sdk/src/generate/runtime-templates.tsindex e0e8e044d1c..35e3e233ebf 100644--- a/packages/twenty-client-sdk/src/generate/genql/runtime-templates.ts+++ b/packages/twenty-client-sdk/src/generate/runtime-templates.ts@@ -6,22 +6,22 @@// `?raw` only resolves under Vite. When this module runs outside a Vite bundle// — e.g. `tsx scripts/generate-metadata-client.ts`, which backs the// `generate-metadata-client` target and server-validation — the `?raw` imports-// are `undefined`, so we fall back to reading the sibling source files from+// are `undefined`, so we fall back to reading the source files from// disk. In the bundled build the imports are defined and the fallback is never// reached, so the shipped runtime is unchanged.import { readFileSync } from 'node:fs';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';-import batcher from './runtime/batcher.ts?raw';-import createClient from './runtime/createClient.ts?raw';-import error from './runtime/error.ts?raw';-import fetcher from './runtime/fetcher.ts?raw';-import generateGraphqlOperation from './runtime/generateGraphqlOperation.ts?raw';-import index from './runtime/index.ts?raw';-import linkTypeMap from './runtime/linkTypeMap.ts?raw';-import typeSelection from './runtime/typeSelection.ts?raw';-import types from './runtime/types.ts?raw';+import batcher from './genql/runtime/batcher.ts?raw';+import createClient from './genql/runtime/createClient.ts?raw';+import error from './genql/runtime/error.ts?raw';+import fetcher from './genql/runtime/fetcher.ts?raw';+import generateGraphqlOperation from './genql/runtime/generateGraphqlOperation.ts?raw';+import index from './genql/runtime/index.ts?raw';+import linkTypeMap from './genql/runtime/linkTypeMap.ts?raw';+import typeSelection from './genql/runtime/typeSelection.ts?raw';+import types from './genql/runtime/types.ts?raw';const readTemplate = (bundled: string | undefined,@@ -29,7 +29,11 @@ const readTemplate = (): string => {if (bundled !== undefined) return bundled;- const runtimeDir = join(dirname(fileURLToPath(import.meta.url)), 'runtime');+ const runtimeDir = join(+ dirname(fileURLToPath(import.meta.url)),+ 'genql',+ 'runtime',+ );return readFileSync(join(runtimeDir, fileName), 'utf-8');};diff --git a/packages/twenty-client-sdk/tsconfig.lib.json b/packages/twenty-client-sdk/tsconfig.lib.jsonindex 4a9ce13e93e..f75975d3904 100644--- a/packages/twenty-client-sdk/tsconfig.lib.json+++ b/packages/twenty-client-sdk/tsconfig.lib.json@@ -13,5 +13,11 @@"sourceMap": true},"include": ["src"],- "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]+ "exclude": [+ "node_modules",+ "dist",+ "**/*.test.ts",+ "**/*.spec.ts",+ "**/__tests__/**"+ ]}