@uidu/client 3.4.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @uidu/client
2
2
 
3
+ ## 3.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 45e1997: Normalize `fieldValuesAttributes[].content` on every mutation.
8
+
9
+ The API stores each field value as JSON and reads it back as `content['value']`,
10
+ so `content` must always be `{ value: … }`. A bare scalar wasn't rejected at the
11
+ mutation boundary — the record saved, the server-side typed columns stayed
12
+ empty, and later reads of that field errored out. Code-generating agents hit
13
+ this constantly, since `FieldValueAttributes.content` is typed as an untyped
14
+ `JSON` scalar.
15
+
16
+ `UiduClient.mutate` now wraps a bare `content` in `{ value }` before sending,
17
+ and warns once per mutation outside production so the call site gets fixed.
18
+ Doing it in `mutate` rather than per function covers all ~50 authoring
19
+ mutations and reaches `fieldValuesAttributes` wherever it nests — under
20
+ `contactAttributes.contactableAttributes`, inside `pageBlocksAttributes[]`, and
21
+ on the 15 other `*Attributes` types that carry it. Already-wrapped payloads,
22
+ `content` payloads themselves, the caller's object, and every untouched subtree
23
+ are left alone by reference. Reads (`query`) are unaffected.
24
+
25
+ The helpers are exported as `normalizeFieldValueContent` and
26
+ `normalizeFieldValuesAttributes` for callers that assemble
27
+ `fieldValuesAttributes` outside the SDK.
28
+
3
29
  ## 3.4.1
4
30
 
5
31
  ### Patch Changes
@@ -3,10 +3,11 @@ export { UiduError } from "./types.js";
3
3
  export type { UiduClientConfig, UiduErrorOptions } from "./types.js";
4
4
  export { paginate } from "./utils/paginate.js";
5
5
  export type { PaginateOptions } from "./utils/paginate.js";
6
+ export { normalizeFieldValueContent, normalizeFieldValuesAttributes, } from "./utils/fieldValues.js";
6
7
  export { ListApplicationsDocument, ListBookingsDocument, ListCalendarsDocument, ListCalendarEventsDocument, ListCallsDocument, ListCampaignsDocument, ListEmailCampaignsDocument, ListCoursesDocument, ListDealsDocument, ListDonationCampaignsDocument, ListEmployeesDocument, ListEnrollmentsDocument, ListEventsDocument, ListFormsDocument, ListKbArticlesDocument, ListKbCollectionsDocument, ListLecturesDocument, ListPagesDocument, ListStoriesDocument, } from "./generated/index.js";
7
8
  export { getPage, listPages, getTemplate, createProject, createPage, createPageBlock, createFieldValue, } from "./cms.js";
8
9
  export type { Page, Template } from "./cms.js";
9
- export { createWorkspace, generateWorkspaceApiCredentials, } from "./system.js";
10
+ export { createWorkspace, generateWorkspaceApiCredentials } from "./system.js";
10
11
  export { createSpace } from "./spaces.js";
11
12
  export { createTask } from "./tasks.js";
12
13
  export { createNote } from "./notes.js";
@@ -35,9 +36,9 @@ export { getBooking, listBookings, getCalendar, listCalendars, getCalendarEvent,
35
36
  export type { Booking, Calendar, CalendarEvent } from "./bookings.js";
36
37
  export { getCourse, listCourses, getEnrollment, listEnrollments, getLecture, listLectures, } from "./courses.js";
37
38
  export type { Course, Enrollment, Lecture } from "./courses.js";
38
- export { getCampaign, listCampaigns, listEmailCampaigns, } from "./campaigns.js";
39
+ export { getCampaign, listCampaigns, listEmailCampaigns } from "./campaigns.js";
39
40
  export type { Campaign } from "./campaigns.js";
40
- export { getContact, listContacts, getDeal, listDeals, } from "./contacts.js";
41
+ export { getContact, listContacts, getDeal, listDeals } from "./contacts.js";
41
42
  export type { Contact, Deal } from "./contacts.js";
42
43
  export { getKbArticle, listKbArticles, getKbCollection, listKbCollections, } from "./kb.js";
43
44
  export type { KbArticle, KbCollection } from "./kb.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The API stores every answer in a `content` JSON column and reads it back with
3
+ * `content['value']` — so `content` must always be an object shaped
4
+ * `{ value: <the answer> }`, never the bare answer.
5
+ *
6
+ * Passing a flat scalar (`content: 'hello'`) is the single most common mistake
7
+ * when writing field values by hand or via a code-generating agent: the server
8
+ * accepts the mutation but the typed columns silently stay empty, and later
9
+ * reads of that field blow up. We normalize here so the flat shape is
10
+ * impossible to send rather than merely documented.
11
+ *
12
+ * `fieldValuesAttributes` shows up on 15 different `*Attributes` types and
13
+ * nests arbitrarily (`contactAttributes.contactableAttributes.…`,
14
+ * `pageAttributes.pageBlocksAttributes[].…`), so the walk below is keyed on the
15
+ * property name at any depth rather than on a fixed path. It runs once per
16
+ * mutation in `UiduClient.mutate`.
17
+ */
18
+ type FieldValueLike = {
19
+ content?: unknown;
20
+ } & Record<string, unknown>;
21
+ /**
22
+ * Wrap a `content` payload in `{ value }` unless it already carries a `value`
23
+ * key. Returns the input untouched when there is nothing to do.
24
+ */
25
+ export declare function normalizeFieldValueContent(content: unknown): unknown;
26
+ /**
27
+ * Normalize a standalone `fieldValuesAttributes` array. Exported for callers
28
+ * that assemble one by hand outside an SDK mutation.
29
+ */
30
+ export declare function normalizeFieldValuesAttributes<T extends FieldValueLike>(attributes: ReadonlyArray<T | null | undefined> | null | undefined): typeof attributes;
31
+ /**
32
+ * Normalize every `fieldValuesAttributes` array reachable from a mutation's
33
+ * variables, at any depth. Returns the input untouched — same reference, and
34
+ * same references for every unchanged subtree — when there is nothing to do.
35
+ */
36
+ export declare function normalizeMutationVariables<V>(variables: V): V;
37
+ export {};
@@ -14,6 +14,131 @@ class UiduError extends Error {
14
14
  }
15
15
  }
16
16
 
17
+ /**
18
+ * The API stores every answer in a `content` JSON column and reads it back with
19
+ * `content['value']` — so `content` must always be an object shaped
20
+ * `{ value: <the answer> }`, never the bare answer.
21
+ *
22
+ * Passing a flat scalar (`content: 'hello'`) is the single most common mistake
23
+ * when writing field values by hand or via a code-generating agent: the server
24
+ * accepts the mutation but the typed columns silently stay empty, and later
25
+ * reads of that field blow up. We normalize here so the flat shape is
26
+ * impossible to send rather than merely documented.
27
+ *
28
+ * `fieldValuesAttributes` shows up on 15 different `*Attributes` types and
29
+ * nests arbitrarily (`contactAttributes.contactableAttributes.…`,
30
+ * `pageAttributes.pageBlocksAttributes[].…`), so the walk below is keyed on the
31
+ * property name at any depth rather than on a fixed path. It runs once per
32
+ * mutation in `UiduClient.mutate`.
33
+ */
34
+
35
+ const FIELD_VALUES_KEY = 'fieldValuesAttributes';
36
+ function isPlainObject(value) {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ }
39
+ function isDev() {
40
+ // Read `process` off globalThis: this file is compiled by consumers that
41
+ // don't pull in @types/node (e.g. @uidu/react), and it has to stay safe in
42
+ // browser and edge runtimes where `process` is absent entirely.
43
+ const env = globalThis.process?.env;
44
+ return env?.NODE_ENV !== 'production';
45
+ }
46
+ function warnOnce(state) {
47
+ if (!state.rewrote || !isDev()) return;
48
+ console.warn('[@uidu/client] fieldValuesAttributes: `content` must be `{ value: … }`, ' + 'not a bare value. Wrapping it for you — update the call site, since ' + 'other clients of the API will not do this.');
49
+ }
50
+
51
+ /**
52
+ * Wrap a `content` payload in `{ value }` unless it already carries a `value`
53
+ * key. Returns the input untouched when there is nothing to do.
54
+ */
55
+ function normalizeFieldValueContent(content) {
56
+ if (content === undefined || content === null) return content;
57
+ if (isPlainObject(content) && 'value' in content) return content;
58
+ return {
59
+ value: content
60
+ };
61
+ }
62
+
63
+ /** Walk any value, rewriting `fieldValuesAttributes` arrays wherever they sit. */
64
+ function walk(value, state) {
65
+ if (Array.isArray(value)) return walkArray(value, state);
66
+ if (!isPlainObject(value)) return value;
67
+ let changed = false;
68
+ const next = {};
69
+ for (const [key, child] of Object.entries(value)) {
70
+ const rewritten = key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
71
+ if (rewritten !== child) changed = true;
72
+ next[key] = rewritten;
73
+ }
74
+ return changed ? next : value;
75
+ }
76
+ function walkArray(values, state) {
77
+ let changed = false;
78
+ const next = values.map(item => {
79
+ const rewritten = walk(item, state);
80
+ if (rewritten !== item) changed = true;
81
+ return rewritten;
82
+ });
83
+ return changed ? next : values;
84
+ }
85
+
86
+ /**
87
+ * Normalize the entries of one `fieldValuesAttributes` array: wrap `content`,
88
+ * and keep walking every sibling key (`linkedRecordAttributes`, nested
89
+ * `fieldValuesAttributes`, …). Deliberately does not descend into `content`
90
+ * itself — that payload is opaque user JSON.
91
+ */
92
+ function walkEntries(entries, state) {
93
+ let arrayChanged = false;
94
+ const next = entries.map(entry => {
95
+ if (!isPlainObject(entry)) return entry;
96
+ let changed = false;
97
+ const rewritten = {};
98
+ for (const [key, child] of Object.entries(entry)) {
99
+ const value = key === 'content' ? normalizeFieldValueContent(child) : key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
100
+ if (value !== child) {
101
+ changed = true;
102
+ if (key === 'content') state.rewrote = true;
103
+ }
104
+ rewritten[key] = value;
105
+ }
106
+ if (!changed) return entry;
107
+ arrayChanged = true;
108
+ return rewritten;
109
+ });
110
+ return arrayChanged ? next : entries;
111
+ }
112
+
113
+ /**
114
+ * Normalize a standalone `fieldValuesAttributes` array. Exported for callers
115
+ * that assemble one by hand outside an SDK mutation.
116
+ */
117
+ function normalizeFieldValuesAttributes(attributes) {
118
+ if (!attributes) return attributes;
119
+ const state = {
120
+ rewrote: false
121
+ };
122
+ const normalized = walkEntries(attributes, state);
123
+ warnOnce(state);
124
+ return normalized;
125
+ }
126
+
127
+ /**
128
+ * Normalize every `fieldValuesAttributes` array reachable from a mutation's
129
+ * variables, at any depth. Returns the input untouched — same reference, and
130
+ * same references for every unchanged subtree — when there is nothing to do.
131
+ */
132
+ function normalizeMutationVariables(variables) {
133
+ if (!isPlainObject(variables) && !Array.isArray(variables)) return variables;
134
+ const state = {
135
+ rewrote: false
136
+ };
137
+ const normalized = walk(variables, state);
138
+ warnOnce(state);
139
+ return normalized;
140
+ }
141
+
17
142
  class UiduClient {
18
143
  constructor(config) {
19
144
  this.endpoint = config.endpoint ?? `https://${config.workspace}.uidu.org/graphql`;
@@ -34,7 +159,10 @@ class UiduClient {
34
159
  }
35
160
  }
36
161
  mutate(document, variables) {
37
- return this.query(document, variables);
162
+ // `fieldValuesAttributes[].content` must be `{ value: … }`; a bare value is
163
+ // accepted by the API but silently discarded. Fix it up for every mutation
164
+ // rather than at each of the ~50 call sites. See ./utils/fieldValues.
165
+ return this.query(document, normalizeMutationVariables(variables));
38
166
  }
39
167
  }
40
168
  function createClient(config) {
@@ -819,6 +947,8 @@ exports.listOffices = listOffices;
819
947
  exports.listPages = listPages;
820
948
  exports.listRoles = listRoles;
821
949
  exports.listStories = listStories;
950
+ exports.normalizeFieldValueContent = normalizeFieldValueContent;
951
+ exports.normalizeFieldValuesAttributes = normalizeFieldValuesAttributes;
822
952
  exports.paginate = paginate;
823
953
  exports.search = search;
824
954
  exports.terminateEmployment = terminateEmployment;
@@ -14,6 +14,131 @@ class UiduError extends Error {
14
14
  }
15
15
  }
16
16
 
17
+ /**
18
+ * The API stores every answer in a `content` JSON column and reads it back with
19
+ * `content['value']` — so `content` must always be an object shaped
20
+ * `{ value: <the answer> }`, never the bare answer.
21
+ *
22
+ * Passing a flat scalar (`content: 'hello'`) is the single most common mistake
23
+ * when writing field values by hand or via a code-generating agent: the server
24
+ * accepts the mutation but the typed columns silently stay empty, and later
25
+ * reads of that field blow up. We normalize here so the flat shape is
26
+ * impossible to send rather than merely documented.
27
+ *
28
+ * `fieldValuesAttributes` shows up on 15 different `*Attributes` types and
29
+ * nests arbitrarily (`contactAttributes.contactableAttributes.…`,
30
+ * `pageAttributes.pageBlocksAttributes[].…`), so the walk below is keyed on the
31
+ * property name at any depth rather than on a fixed path. It runs once per
32
+ * mutation in `UiduClient.mutate`.
33
+ */
34
+
35
+ const FIELD_VALUES_KEY = 'fieldValuesAttributes';
36
+ function isPlainObject(value) {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ }
39
+ function isDev() {
40
+ // Read `process` off globalThis: this file is compiled by consumers that
41
+ // don't pull in @types/node (e.g. @uidu/react), and it has to stay safe in
42
+ // browser and edge runtimes where `process` is absent entirely.
43
+ const env = globalThis.process?.env;
44
+ return env?.NODE_ENV !== 'production';
45
+ }
46
+ function warnOnce(state) {
47
+ if (!state.rewrote || !isDev()) return;
48
+ console.warn('[@uidu/client] fieldValuesAttributes: `content` must be `{ value: … }`, ' + 'not a bare value. Wrapping it for you — update the call site, since ' + 'other clients of the API will not do this.');
49
+ }
50
+
51
+ /**
52
+ * Wrap a `content` payload in `{ value }` unless it already carries a `value`
53
+ * key. Returns the input untouched when there is nothing to do.
54
+ */
55
+ function normalizeFieldValueContent(content) {
56
+ if (content === undefined || content === null) return content;
57
+ if (isPlainObject(content) && 'value' in content) return content;
58
+ return {
59
+ value: content
60
+ };
61
+ }
62
+
63
+ /** Walk any value, rewriting `fieldValuesAttributes` arrays wherever they sit. */
64
+ function walk(value, state) {
65
+ if (Array.isArray(value)) return walkArray(value, state);
66
+ if (!isPlainObject(value)) return value;
67
+ let changed = false;
68
+ const next = {};
69
+ for (const [key, child] of Object.entries(value)) {
70
+ const rewritten = key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
71
+ if (rewritten !== child) changed = true;
72
+ next[key] = rewritten;
73
+ }
74
+ return changed ? next : value;
75
+ }
76
+ function walkArray(values, state) {
77
+ let changed = false;
78
+ const next = values.map(item => {
79
+ const rewritten = walk(item, state);
80
+ if (rewritten !== item) changed = true;
81
+ return rewritten;
82
+ });
83
+ return changed ? next : values;
84
+ }
85
+
86
+ /**
87
+ * Normalize the entries of one `fieldValuesAttributes` array: wrap `content`,
88
+ * and keep walking every sibling key (`linkedRecordAttributes`, nested
89
+ * `fieldValuesAttributes`, …). Deliberately does not descend into `content`
90
+ * itself — that payload is opaque user JSON.
91
+ */
92
+ function walkEntries(entries, state) {
93
+ let arrayChanged = false;
94
+ const next = entries.map(entry => {
95
+ if (!isPlainObject(entry)) return entry;
96
+ let changed = false;
97
+ const rewritten = {};
98
+ for (const [key, child] of Object.entries(entry)) {
99
+ const value = key === 'content' ? normalizeFieldValueContent(child) : key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
100
+ if (value !== child) {
101
+ changed = true;
102
+ if (key === 'content') state.rewrote = true;
103
+ }
104
+ rewritten[key] = value;
105
+ }
106
+ if (!changed) return entry;
107
+ arrayChanged = true;
108
+ return rewritten;
109
+ });
110
+ return arrayChanged ? next : entries;
111
+ }
112
+
113
+ /**
114
+ * Normalize a standalone `fieldValuesAttributes` array. Exported for callers
115
+ * that assemble one by hand outside an SDK mutation.
116
+ */
117
+ function normalizeFieldValuesAttributes(attributes) {
118
+ if (!attributes) return attributes;
119
+ const state = {
120
+ rewrote: false
121
+ };
122
+ const normalized = walkEntries(attributes, state);
123
+ warnOnce(state);
124
+ return normalized;
125
+ }
126
+
127
+ /**
128
+ * Normalize every `fieldValuesAttributes` array reachable from a mutation's
129
+ * variables, at any depth. Returns the input untouched — same reference, and
130
+ * same references for every unchanged subtree — when there is nothing to do.
131
+ */
132
+ function normalizeMutationVariables(variables) {
133
+ if (!isPlainObject(variables) && !Array.isArray(variables)) return variables;
134
+ const state = {
135
+ rewrote: false
136
+ };
137
+ const normalized = walk(variables, state);
138
+ warnOnce(state);
139
+ return normalized;
140
+ }
141
+
17
142
  class UiduClient {
18
143
  constructor(config) {
19
144
  this.endpoint = config.endpoint ?? `https://${config.workspace}.uidu.org/graphql`;
@@ -34,7 +159,10 @@ class UiduClient {
34
159
  }
35
160
  }
36
161
  mutate(document, variables) {
37
- return this.query(document, variables);
162
+ // `fieldValuesAttributes[].content` must be `{ value: … }`; a bare value is
163
+ // accepted by the API but silently discarded. Fix it up for every mutation
164
+ // rather than at each of the ~50 call sites. See ./utils/fieldValues.
165
+ return this.query(document, normalizeMutationVariables(variables));
38
166
  }
39
167
  }
40
168
  function createClient(config) {
@@ -819,6 +947,8 @@ exports.listOffices = listOffices;
819
947
  exports.listPages = listPages;
820
948
  exports.listRoles = listRoles;
821
949
  exports.listStories = listStories;
950
+ exports.normalizeFieldValueContent = normalizeFieldValueContent;
951
+ exports.normalizeFieldValuesAttributes = normalizeFieldValuesAttributes;
822
952
  exports.paginate = paginate;
823
953
  exports.search = search;
824
954
  exports.terminateEmployment = terminateEmployment;
@@ -10,6 +10,131 @@ class UiduError extends Error {
10
10
  }
11
11
  }
12
12
 
13
+ /**
14
+ * The API stores every answer in a `content` JSON column and reads it back with
15
+ * `content['value']` — so `content` must always be an object shaped
16
+ * `{ value: <the answer> }`, never the bare answer.
17
+ *
18
+ * Passing a flat scalar (`content: 'hello'`) is the single most common mistake
19
+ * when writing field values by hand or via a code-generating agent: the server
20
+ * accepts the mutation but the typed columns silently stay empty, and later
21
+ * reads of that field blow up. We normalize here so the flat shape is
22
+ * impossible to send rather than merely documented.
23
+ *
24
+ * `fieldValuesAttributes` shows up on 15 different `*Attributes` types and
25
+ * nests arbitrarily (`contactAttributes.contactableAttributes.…`,
26
+ * `pageAttributes.pageBlocksAttributes[].…`), so the walk below is keyed on the
27
+ * property name at any depth rather than on a fixed path. It runs once per
28
+ * mutation in `UiduClient.mutate`.
29
+ */
30
+
31
+ const FIELD_VALUES_KEY = 'fieldValuesAttributes';
32
+ function isPlainObject(value) {
33
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
34
+ }
35
+ function isDev() {
36
+ // Read `process` off globalThis: this file is compiled by consumers that
37
+ // don't pull in @types/node (e.g. @uidu/react), and it has to stay safe in
38
+ // browser and edge runtimes where `process` is absent entirely.
39
+ const env = globalThis.process?.env;
40
+ return env?.NODE_ENV !== 'production';
41
+ }
42
+ function warnOnce(state) {
43
+ if (!state.rewrote || !isDev()) return;
44
+ console.warn('[@uidu/client] fieldValuesAttributes: `content` must be `{ value: … }`, ' + 'not a bare value. Wrapping it for you — update the call site, since ' + 'other clients of the API will not do this.');
45
+ }
46
+
47
+ /**
48
+ * Wrap a `content` payload in `{ value }` unless it already carries a `value`
49
+ * key. Returns the input untouched when there is nothing to do.
50
+ */
51
+ function normalizeFieldValueContent(content) {
52
+ if (content === undefined || content === null) return content;
53
+ if (isPlainObject(content) && 'value' in content) return content;
54
+ return {
55
+ value: content
56
+ };
57
+ }
58
+
59
+ /** Walk any value, rewriting `fieldValuesAttributes` arrays wherever they sit. */
60
+ function walk(value, state) {
61
+ if (Array.isArray(value)) return walkArray(value, state);
62
+ if (!isPlainObject(value)) return value;
63
+ let changed = false;
64
+ const next = {};
65
+ for (const [key, child] of Object.entries(value)) {
66
+ const rewritten = key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
67
+ if (rewritten !== child) changed = true;
68
+ next[key] = rewritten;
69
+ }
70
+ return changed ? next : value;
71
+ }
72
+ function walkArray(values, state) {
73
+ let changed = false;
74
+ const next = values.map(item => {
75
+ const rewritten = walk(item, state);
76
+ if (rewritten !== item) changed = true;
77
+ return rewritten;
78
+ });
79
+ return changed ? next : values;
80
+ }
81
+
82
+ /**
83
+ * Normalize the entries of one `fieldValuesAttributes` array: wrap `content`,
84
+ * and keep walking every sibling key (`linkedRecordAttributes`, nested
85
+ * `fieldValuesAttributes`, …). Deliberately does not descend into `content`
86
+ * itself — that payload is opaque user JSON.
87
+ */
88
+ function walkEntries(entries, state) {
89
+ let arrayChanged = false;
90
+ const next = entries.map(entry => {
91
+ if (!isPlainObject(entry)) return entry;
92
+ let changed = false;
93
+ const rewritten = {};
94
+ for (const [key, child] of Object.entries(entry)) {
95
+ const value = key === 'content' ? normalizeFieldValueContent(child) : key === FIELD_VALUES_KEY && Array.isArray(child) ? walkEntries(child, state) : walk(child, state);
96
+ if (value !== child) {
97
+ changed = true;
98
+ if (key === 'content') state.rewrote = true;
99
+ }
100
+ rewritten[key] = value;
101
+ }
102
+ if (!changed) return entry;
103
+ arrayChanged = true;
104
+ return rewritten;
105
+ });
106
+ return arrayChanged ? next : entries;
107
+ }
108
+
109
+ /**
110
+ * Normalize a standalone `fieldValuesAttributes` array. Exported for callers
111
+ * that assemble one by hand outside an SDK mutation.
112
+ */
113
+ function normalizeFieldValuesAttributes(attributes) {
114
+ if (!attributes) return attributes;
115
+ const state = {
116
+ rewrote: false
117
+ };
118
+ const normalized = walkEntries(attributes, state);
119
+ warnOnce(state);
120
+ return normalized;
121
+ }
122
+
123
+ /**
124
+ * Normalize every `fieldValuesAttributes` array reachable from a mutation's
125
+ * variables, at any depth. Returns the input untouched — same reference, and
126
+ * same references for every unchanged subtree — when there is nothing to do.
127
+ */
128
+ function normalizeMutationVariables(variables) {
129
+ if (!isPlainObject(variables) && !Array.isArray(variables)) return variables;
130
+ const state = {
131
+ rewrote: false
132
+ };
133
+ const normalized = walk(variables, state);
134
+ warnOnce(state);
135
+ return normalized;
136
+ }
137
+
13
138
  class UiduClient {
14
139
  constructor(config) {
15
140
  this.endpoint = config.endpoint ?? `https://${config.workspace}.uidu.org/graphql`;
@@ -30,7 +155,10 @@ class UiduClient {
30
155
  }
31
156
  }
32
157
  mutate(document, variables) {
33
- return this.query(document, variables);
158
+ // `fieldValuesAttributes[].content` must be `{ value: … }`; a bare value is
159
+ // accepted by the API but silently discarded. Fix it up for every mutation
160
+ // rather than at each of the ~50 call sites. See ./utils/fieldValues.
161
+ return this.query(document, normalizeMutationVariables(variables));
34
162
  }
35
163
  }
36
164
  function createClient(config) {
@@ -706,4 +834,4 @@ async function listKbCollections(client, variables = {}) {
706
834
  return nodes(result.currentWorkspace?.kbCollections);
707
835
  }
708
836
 
709
- export { ListApplicationsDocument, ListBookingsDocument, ListCalendarEventsDocument, ListCalendarsDocument, ListCallsDocument, ListCampaignsDocument, ListCoursesDocument, ListDealsDocument, ListDonationCampaignsDocument, ListEmailCampaignsDocument, ListEmployeesDocument, ListEnrollmentsDocument, ListEventsDocument, ListFormsDocument, ListKbArticlesDocument, ListKbCollectionsDocument, ListLecturesDocument, ListPagesDocument, ListStoriesDocument, UiduClient, UiduError, contractEvents, createApplication, createAttendance, createChannel, createClient, createCompensation, createContact, createCourse, createDeal, createDonation, createDonationCampaign, createEmployee, createEmployment, createEvent, createFieldValue, createForm, createFormResponse, createKbArticle, createKbCollection, createNote, createPage, createPageBlock, createProject, createSpace, createStory, createTask, createWorkspace, deleteChannel, deleteCompensation, deleteContact, deleteCourse, deleteDonationCampaign, deleteEmployment, deleteForm, deleteKbArticle, deleteKbCollection, deleteNote, deleteSpace, deleteTask, generateWorkspaceApiCredentials, getBooking, getCalendar, getCalendarEvent, getCall, getCampaign, getChannel, getContact, getCourse, getDeal, getDonationCampaign, getEmployee, getEnrollment, getEvent, getForm, getJob, getKbArticle, getKbCollection, getLecture, getPage, getStory, getTemplate, listApplications, listBookings, listCalendarEvents, listCalendars, listCalls, listCampaigns, listCcnls, listCircles, listContacts, listCourses, listDeals, listDonationCampaigns, listEmailCampaigns, listEmployees, listEmploymentHistory, listEnrollments, listEvents, listForms, listJobs, listKbArticles, listKbCollections, listKinds, listLectures, listOffices, listPages, listRoles, listStories, paginate, search, terminateEmployment, updateChannel, updateCompensation, updateCourse, updateDeal, updateDonationCampaign, updateEmployee, updateEmployment, updateEvent, updateForm, updateFormResponse, updateKbArticle, updateKbCollection, updateNote, updateSpace, updateStory, updateTask, weekStartFor };
837
+ export { ListApplicationsDocument, ListBookingsDocument, ListCalendarEventsDocument, ListCalendarsDocument, ListCallsDocument, ListCampaignsDocument, ListCoursesDocument, ListDealsDocument, ListDonationCampaignsDocument, ListEmailCampaignsDocument, ListEmployeesDocument, ListEnrollmentsDocument, ListEventsDocument, ListFormsDocument, ListKbArticlesDocument, ListKbCollectionsDocument, ListLecturesDocument, ListPagesDocument, ListStoriesDocument, UiduClient, UiduError, contractEvents, createApplication, createAttendance, createChannel, createClient, createCompensation, createContact, createCourse, createDeal, createDonation, createDonationCampaign, createEmployee, createEmployment, createEvent, createFieldValue, createForm, createFormResponse, createKbArticle, createKbCollection, createNote, createPage, createPageBlock, createProject, createSpace, createStory, createTask, createWorkspace, deleteChannel, deleteCompensation, deleteContact, deleteCourse, deleteDonationCampaign, deleteEmployment, deleteForm, deleteKbArticle, deleteKbCollection, deleteNote, deleteSpace, deleteTask, generateWorkspaceApiCredentials, getBooking, getCalendar, getCalendarEvent, getCall, getCampaign, getChannel, getContact, getCourse, getDeal, getDonationCampaign, getEmployee, getEnrollment, getEvent, getForm, getJob, getKbArticle, getKbCollection, getLecture, getPage, getStory, getTemplate, listApplications, listBookings, listCalendarEvents, listCalendars, listCalls, listCampaigns, listCcnls, listCircles, listContacts, listCourses, listDeals, listDonationCampaigns, listEmailCampaigns, listEmployees, listEmploymentHistory, listEnrollments, listEvents, listForms, listJobs, listKbArticles, listKbCollections, listKinds, listLectures, listOffices, listPages, listRoles, listStories, normalizeFieldValueContent, normalizeFieldValuesAttributes, paginate, search, terminateEmployment, updateChannel, updateCompensation, updateCourse, updateDeal, updateDonationCampaign, updateEmployee, updateEmployment, updateEvent, updateForm, updateFormResponse, updateKbArticle, updateKbCollection, updateNote, updateSpace, updateStory, updateTask, weekStartFor };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uidu/client",
3
- "version": "3.4.1",
3
+ "version": "3.5.0",
4
4
  "description": "Typed GraphQL client for the uidu platform. Server-first, framework-agnostic.",
5
5
  "license": "MIT",
6
6
  "author": "uidu",
@@ -0,0 +1,165 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ const request = vi.fn();
4
+
5
+ vi.mock('graphql-request', () => ({
6
+ GraphQLClient: class {
7
+ request = request;
8
+ },
9
+ ClientError: class extends Error {},
10
+ }));
11
+
12
+ const { createClient } = await import('./client');
13
+ const { createFormResponse } = await import('./forms');
14
+ const { CreateFormResponseDocument, CreatePageDocument, GetFormDocument } =
15
+ await import('./generated');
16
+
17
+ const client = createClient({ workspace: 'acme', apiKey: 'k' });
18
+
19
+ beforeEach(() => {
20
+ request.mockResolvedValue({});
21
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
22
+ });
23
+
24
+ afterEach(() => {
25
+ vi.restoreAllMocks();
26
+ request.mockReset();
27
+ });
28
+
29
+ const sentVariables = () => request.mock.calls[0][1];
30
+
31
+ describe('UiduClient.mutate — fieldValuesAttributes normalization', () => {
32
+ it('wraps a flat `content` on a form response', async () => {
33
+ await createFormResponse(client, {
34
+ input: {
35
+ event: 'complete!',
36
+ attributes: {
37
+ formId: 'form_1',
38
+ fieldValuesAttributes: [
39
+ { fieldId: 'f1', content: 'hello' },
40
+ { fieldId: 'f2', content: { value: 'already wrapped' } },
41
+ ],
42
+ },
43
+ },
44
+ });
45
+
46
+ expect(sentVariables().input.attributes.fieldValuesAttributes).toEqual([
47
+ { fieldId: 'f1', content: { value: 'hello' } },
48
+ { fieldId: 'f2', content: { value: 'already wrapped' } },
49
+ ]);
50
+ });
51
+
52
+ it('reaches nested attributes (contactAttributes.contactableAttributes)', async () => {
53
+ await client.mutate(CreateFormResponseDocument, {
54
+ input: {
55
+ attributes: {
56
+ formId: 'form_1',
57
+ contactAttributes: {
58
+ email: 'a@b.c',
59
+ contactableAttributes: {
60
+ kind: 'person',
61
+ fieldValuesAttributes: [{ fieldId: 'f9', content: 'nested' }],
62
+ },
63
+ },
64
+ },
65
+ },
66
+ } as never);
67
+
68
+ expect(
69
+ sentVariables().input.attributes.contactAttributes.contactableAttributes
70
+ .fieldValuesAttributes,
71
+ ).toEqual([{ fieldId: 'f9', content: { value: 'nested' } }]);
72
+ });
73
+
74
+ it('reaches through arrays (pageBlocksAttributes[])', async () => {
75
+ await client.mutate(CreatePageDocument, {
76
+ input: {
77
+ attributes: {
78
+ name: 'Home',
79
+ pageBlocksAttributes: [
80
+ { fieldValuesAttributes: [{ fieldId: 'f1', content: 'a' }] },
81
+ {
82
+ fieldValuesAttributes: [
83
+ { fieldId: 'f2', content: { value: 'b' } },
84
+ ],
85
+ },
86
+ ],
87
+ },
88
+ },
89
+ } as never);
90
+
91
+ expect(sentVariables().input.attributes.pageBlocksAttributes).toEqual([
92
+ { fieldValuesAttributes: [{ fieldId: 'f1', content: { value: 'a' } }] },
93
+ { fieldValuesAttributes: [{ fieldId: 'f2', content: { value: 'b' } }] },
94
+ ]);
95
+ });
96
+
97
+ it('does not descend into the `content` payload itself', async () => {
98
+ const doc = {
99
+ type: 'doc',
100
+ // a rich text document that happens to carry the magic key
101
+ fieldValuesAttributes: [{ fieldId: 'nope', content: 'leave me' }],
102
+ };
103
+
104
+ await client.mutate(CreateFormResponseDocument, {
105
+ input: {
106
+ attributes: {
107
+ fieldValuesAttributes: [{ fieldId: 'f1', content: { value: doc } }],
108
+ },
109
+ },
110
+ } as never);
111
+
112
+ expect(
113
+ sentVariables().input.attributes.fieldValuesAttributes[0].content.value,
114
+ ).toEqual(doc);
115
+ });
116
+
117
+ it('leaves mutations without field values untouched, by reference', async () => {
118
+ const variables = {
119
+ input: { attributes: { name: 'Home', slug: 'home' } },
120
+ };
121
+ await client.mutate(CreatePageDocument, variables as never);
122
+
123
+ expect(sentVariables()).toBe(variables);
124
+ });
125
+
126
+ it('does not mutate the caller’s object', async () => {
127
+ const variables = {
128
+ input: {
129
+ attributes: {
130
+ fieldValuesAttributes: [{ fieldId: 'f1', content: 'flat' }],
131
+ },
132
+ },
133
+ };
134
+ await client.mutate(CreateFormResponseDocument, variables as never);
135
+
136
+ expect(variables.input.attributes.fieldValuesAttributes[0].content).toBe(
137
+ 'flat',
138
+ );
139
+ });
140
+
141
+ it('warns once per mutation, not once per entry', async () => {
142
+ await client.mutate(CreateFormResponseDocument, {
143
+ input: {
144
+ attributes: {
145
+ fieldValuesAttributes: [
146
+ { fieldId: 'f1', content: 'a' },
147
+ { fieldId: 'f2', content: 'b' },
148
+ { fieldId: 'f3', content: 'c' },
149
+ ],
150
+ },
151
+ },
152
+ } as never);
153
+
154
+ expect(console.warn).toHaveBeenCalledTimes(1);
155
+ });
156
+ });
157
+
158
+ describe('UiduClient.query', () => {
159
+ it('does not normalize — reads have no field value payloads', async () => {
160
+ const variables = { id: 'form_1' };
161
+ await client.query(GetFormDocument, variables);
162
+
163
+ expect(sentVariables()).toBe(variables);
164
+ });
165
+ });
package/src/client.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
2
2
  import { ClientError, GraphQLClient } from 'graphql-request';
3
3
  import { UiduError, type UiduClientConfig } from './types';
4
+ import { normalizeMutationVariables } from './utils/fieldValues';
4
5
 
5
6
  export class UiduClient {
6
7
  readonly endpoint: string;
@@ -35,7 +36,10 @@ export class UiduClient {
35
36
  document: TypedDocumentNode<TResult, TVariables>,
36
37
  variables?: TVariables,
37
38
  ): Promise<TResult> {
38
- return this.query(document, variables);
39
+ // `fieldValuesAttributes[].content` must be `{ value: … }`; a bare value is
40
+ // accepted by the API but silently discarded. Fix it up for every mutation
41
+ // rather than at each of the ~50 call sites. See ./utils/fieldValues.
42
+ return this.query(document, normalizeMutationVariables(variables));
39
43
  }
40
44
  }
41
45
 
package/src/index.ts CHANGED
@@ -5,6 +5,11 @@ export type { UiduClientConfig, UiduErrorOptions } from './types';
5
5
  export { paginate } from './utils/paginate';
6
6
  export type { PaginateOptions } from './utils/paginate';
7
7
 
8
+ export {
9
+ normalizeFieldValueContent,
10
+ normalizeFieldValuesAttributes,
11
+ } from './utils/fieldValues';
12
+
8
13
  export {
9
14
  ListApplicationsDocument,
10
15
  ListBookingsDocument,
@@ -38,10 +43,7 @@ export {
38
43
  } from './cms';
39
44
  export type { Page, Template } from './cms';
40
45
 
41
- export {
42
- createWorkspace,
43
- generateWorkspaceApiCredentials,
44
- } from './system';
46
+ export { createWorkspace, generateWorkspaceApiCredentials } from './system';
45
47
 
46
48
  export { createSpace } from './spaces';
47
49
  export { createTask } from './tasks';
@@ -169,19 +171,10 @@ export {
169
171
  } from './courses';
170
172
  export type { Course, Enrollment, Lecture } from './courses';
171
173
 
172
- export {
173
- getCampaign,
174
- listCampaigns,
175
- listEmailCampaigns,
176
- } from './campaigns';
174
+ export { getCampaign, listCampaigns, listEmailCampaigns } from './campaigns';
177
175
  export type { Campaign } from './campaigns';
178
176
 
179
- export {
180
- getContact,
181
- listContacts,
182
- getDeal,
183
- listDeals,
184
- } from './contacts';
177
+ export { getContact, listContacts, getDeal, listDeals } from './contacts';
185
178
  export type { Contact, Deal } from './contacts';
186
179
 
187
180
  export {
@@ -0,0 +1,268 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import {
3
+ normalizeFieldValueContent,
4
+ normalizeFieldValuesAttributes,
5
+ normalizeMutationVariables,
6
+ } from './fieldValues';
7
+
8
+ afterEach(() => {
9
+ vi.restoreAllMocks();
10
+ });
11
+
12
+ describe('normalizeFieldValueContent', () => {
13
+ it('leaves null and undefined alone', () => {
14
+ expect(normalizeFieldValueContent(null)).toBeNull();
15
+ expect(normalizeFieldValueContent(undefined)).toBeUndefined();
16
+ });
17
+
18
+ it('leaves an already-wrapped payload alone', () => {
19
+ const content = { value: 'hello' };
20
+ expect(normalizeFieldValueContent(content)).toBe(content);
21
+ });
22
+
23
+ it('leaves an explicit null value alone', () => {
24
+ const content = { value: null };
25
+ expect(normalizeFieldValueContent(content)).toBe(content);
26
+ });
27
+
28
+ it('wraps a bare string', () => {
29
+ expect(normalizeFieldValueContent('hello')).toEqual({ value: 'hello' });
30
+ });
31
+
32
+ it('wraps a bare number, boolean and zero', () => {
33
+ expect(normalizeFieldValueContent(42)).toEqual({ value: 42 });
34
+ expect(normalizeFieldValueContent(false)).toEqual({ value: false });
35
+ expect(normalizeFieldValueContent(0)).toEqual({ value: 0 });
36
+ });
37
+
38
+ it('wraps an array (multipleSelect answers)', () => {
39
+ expect(normalizeFieldValueContent(['a', 'b'])).toEqual({
40
+ value: ['a', 'b'],
41
+ });
42
+ });
43
+
44
+ it('wraps an object that has no value key (richText / json answers)', () => {
45
+ const doc = { type: 'doc', content: [] };
46
+ expect(normalizeFieldValueContent(doc)).toEqual({ value: doc });
47
+ });
48
+ });
49
+
50
+ describe('normalizeFieldValuesAttributes', () => {
51
+ it('passes null / undefined through', () => {
52
+ expect(normalizeFieldValuesAttributes(null)).toBeNull();
53
+ expect(normalizeFieldValuesAttributes(undefined)).toBeUndefined();
54
+ });
55
+
56
+ it('returns the same array reference when nothing needs wrapping', () => {
57
+ const attributes = [{ fieldId: '1', content: { value: 'a' } }];
58
+ expect(normalizeFieldValuesAttributes(attributes)).toBe(attributes);
59
+ });
60
+
61
+ it('wraps only the entries that need it, keeping order', () => {
62
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
63
+ const attributes = [
64
+ { fieldId: '1', content: 'flat' },
65
+ { fieldId: '2', content: { value: 'wrapped' } },
66
+ { fieldId: '3', content: 3 },
67
+ ];
68
+
69
+ expect(normalizeFieldValuesAttributes(attributes)).toEqual([
70
+ { fieldId: '1', content: { value: 'flat' } },
71
+ { fieldId: '2', content: { value: 'wrapped' } },
72
+ { fieldId: '3', content: { value: 3 } },
73
+ ]);
74
+ expect(warn).toHaveBeenCalledTimes(1);
75
+ });
76
+
77
+ it('preserves sibling attributes such as id and linkedRecordId', () => {
78
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
79
+ expect(
80
+ normalizeFieldValuesAttributes([
81
+ { fieldId: '1', id: 'fv_1', linkedRecordId: 'lr_1', content: 'x' },
82
+ ]),
83
+ ).toEqual([
84
+ {
85
+ fieldId: '1',
86
+ id: 'fv_1',
87
+ linkedRecordId: 'lr_1',
88
+ content: { value: 'x' },
89
+ },
90
+ ]);
91
+ });
92
+
93
+ it('leaves entries without a content key alone', () => {
94
+ const attributes = [{ fieldId: '1', linkedRecordId: 'lr_1' }];
95
+ expect(normalizeFieldValuesAttributes(attributes)).toBe(attributes);
96
+ });
97
+
98
+ it('does not warn in production', () => {
99
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
100
+ vi.stubEnv('NODE_ENV', 'production');
101
+
102
+ normalizeFieldValuesAttributes([{ fieldId: '1', content: 'flat' }]);
103
+ expect(warn).not.toHaveBeenCalled();
104
+
105
+ vi.unstubAllEnvs();
106
+ });
107
+ });
108
+
109
+ describe('normalizeMutationVariables', () => {
110
+ it('passes non-objects through', () => {
111
+ expect(normalizeMutationVariables(undefined)).toBeUndefined();
112
+ expect(normalizeMutationVariables('x')).toBe('x');
113
+ });
114
+
115
+ it('returns the same object when there is nothing to normalize', () => {
116
+ const variables = {
117
+ input: {
118
+ attributes: {
119
+ formId: 'form_1',
120
+ fieldValuesAttributes: [{ fieldId: '1', content: { value: 'a' } }],
121
+ },
122
+ },
123
+ };
124
+ expect(normalizeMutationVariables(variables)).toBe(variables);
125
+ });
126
+
127
+ it('returns the same object when there are no fieldValuesAttributes', () => {
128
+ const variables = { input: { attributes: { formId: 'form_1' } } };
129
+ expect(normalizeMutationVariables(variables)).toBe(variables);
130
+ });
131
+
132
+ it('rewrites flat content without mutating the caller input', () => {
133
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
134
+ const variables = {
135
+ input: {
136
+ event: 'complete!',
137
+ attributes: {
138
+ formId: 'form_1',
139
+ contactAttributes: { email: 'a@b.c' },
140
+ fieldValuesAttributes: [{ fieldId: '1', content: 'flat' }],
141
+ },
142
+ },
143
+ };
144
+
145
+ expect(normalizeMutationVariables(variables)).toEqual({
146
+ input: {
147
+ event: 'complete!',
148
+ attributes: {
149
+ formId: 'form_1',
150
+ contactAttributes: { email: 'a@b.c' },
151
+ fieldValuesAttributes: [{ fieldId: '1', content: { value: 'flat' } }],
152
+ },
153
+ },
154
+ });
155
+ expect(variables.input.attributes.fieldValuesAttributes[0].content).toBe(
156
+ 'flat',
157
+ );
158
+ });
159
+
160
+ it('finds fieldValuesAttributes nested behind other attributes', () => {
161
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
162
+ const result = normalizeMutationVariables({
163
+ input: {
164
+ attributes: {
165
+ contactAttributes: {
166
+ contactableAttributes: {
167
+ fieldValuesAttributes: [{ fieldId: '1', content: 'deep' }],
168
+ },
169
+ },
170
+ },
171
+ },
172
+ });
173
+
174
+ expect(
175
+ result.input.attributes.contactAttributes.contactableAttributes
176
+ .fieldValuesAttributes,
177
+ ).toEqual([{ fieldId: '1', content: { value: 'deep' } }]);
178
+ });
179
+
180
+ it('finds fieldValuesAttributes inside arrays of attributes', () => {
181
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
182
+ const result = normalizeMutationVariables({
183
+ input: {
184
+ attributes: {
185
+ pageBlocksAttributes: [
186
+ { fieldValuesAttributes: [{ fieldId: '1', content: 'a' }] },
187
+ ],
188
+ },
189
+ },
190
+ });
191
+
192
+ expect(
193
+ result.input.attributes.pageBlocksAttributes[0].fieldValuesAttributes,
194
+ ).toEqual([{ fieldId: '1', content: { value: 'a' } }]);
195
+ });
196
+
197
+ it('shares references for untouched subtrees', () => {
198
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
199
+ const contactAttributes = { email: 'a@b.c' };
200
+ const result = normalizeMutationVariables({
201
+ input: {
202
+ attributes: {
203
+ contactAttributes,
204
+ fieldValuesAttributes: [{ fieldId: '1', content: 'flat' }],
205
+ },
206
+ },
207
+ });
208
+
209
+ expect(result.input.attributes.contactAttributes).toBe(contactAttributes);
210
+ });
211
+
212
+ it('does not descend into a content payload that carries the magic key', () => {
213
+ const doc = {
214
+ fieldValuesAttributes: [{ fieldId: 'nope', content: 'leave me' }],
215
+ };
216
+ const result = normalizeMutationVariables({
217
+ input: {
218
+ attributes: {
219
+ fieldValuesAttributes: [{ fieldId: '1', content: { value: doc } }],
220
+ },
221
+ },
222
+ });
223
+
224
+ expect(result.input.attributes.fieldValuesAttributes[0].content.value).toBe(
225
+ doc,
226
+ );
227
+ });
228
+
229
+ it('normalizes nested field values on a field value entry', () => {
230
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
231
+ const result = normalizeMutationVariables({
232
+ input: {
233
+ attributes: {
234
+ fieldValuesAttributes: [
235
+ {
236
+ fieldId: '1',
237
+ content: { value: 'parent' },
238
+ fieldValuesAttributes: [{ fieldId: '2', content: 'child' }],
239
+ },
240
+ ],
241
+ },
242
+ },
243
+ });
244
+
245
+ expect(
246
+ result.input.attributes.fieldValuesAttributes[0].fieldValuesAttributes,
247
+ ).toEqual([{ fieldId: '2', content: { value: 'child' } }]);
248
+ });
249
+
250
+ it('warns once for a whole mutation, however many entries were wrapped', () => {
251
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
252
+ normalizeMutationVariables({
253
+ input: {
254
+ attributes: {
255
+ fieldValuesAttributes: [
256
+ { fieldId: '1', content: 'a' },
257
+ { fieldId: '2', content: 'b' },
258
+ ],
259
+ pageBlocksAttributes: [
260
+ { fieldValuesAttributes: [{ fieldId: '3', content: 'c' }] },
261
+ ],
262
+ },
263
+ },
264
+ });
265
+
266
+ expect(warn).toHaveBeenCalledTimes(1);
267
+ });
268
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * The API stores every answer in a `content` JSON column and reads it back with
3
+ * `content['value']` — so `content` must always be an object shaped
4
+ * `{ value: <the answer> }`, never the bare answer.
5
+ *
6
+ * Passing a flat scalar (`content: 'hello'`) is the single most common mistake
7
+ * when writing field values by hand or via a code-generating agent: the server
8
+ * accepts the mutation but the typed columns silently stay empty, and later
9
+ * reads of that field blow up. We normalize here so the flat shape is
10
+ * impossible to send rather than merely documented.
11
+ *
12
+ * `fieldValuesAttributes` shows up on 15 different `*Attributes` types and
13
+ * nests arbitrarily (`contactAttributes.contactableAttributes.…`,
14
+ * `pageAttributes.pageBlocksAttributes[].…`), so the walk below is keyed on the
15
+ * property name at any depth rather than on a fixed path. It runs once per
16
+ * mutation in `UiduClient.mutate`.
17
+ */
18
+
19
+ type FieldValueLike = { content?: unknown } & Record<string, unknown>;
20
+
21
+ const FIELD_VALUES_KEY = 'fieldValuesAttributes';
22
+
23
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+
27
+ function isDev(): boolean {
28
+ // Read `process` off globalThis: this file is compiled by consumers that
29
+ // don't pull in @types/node (e.g. @uidu/react), and it has to stay safe in
30
+ // browser and edge runtimes where `process` is absent entirely.
31
+ const env = (
32
+ globalThis as {
33
+ process?: { env?: Record<string, string | undefined> };
34
+ }
35
+ ).process?.env;
36
+
37
+ return env?.NODE_ENV !== 'production';
38
+ }
39
+
40
+ function warnOnce(state: { rewrote: boolean }): void {
41
+ if (!state.rewrote || !isDev()) return;
42
+ console.warn(
43
+ '[@uidu/client] fieldValuesAttributes: `content` must be `{ value: … }`, ' +
44
+ 'not a bare value. Wrapping it for you — update the call site, since ' +
45
+ 'other clients of the API will not do this.',
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Wrap a `content` payload in `{ value }` unless it already carries a `value`
51
+ * key. Returns the input untouched when there is nothing to do.
52
+ */
53
+ export function normalizeFieldValueContent(content: unknown): unknown {
54
+ if (content === undefined || content === null) return content;
55
+ if (isPlainObject(content) && 'value' in content) return content;
56
+ return { value: content };
57
+ }
58
+
59
+ /** Walk any value, rewriting `fieldValuesAttributes` arrays wherever they sit. */
60
+ function walk(value: unknown, state: { rewrote: boolean }): unknown {
61
+ if (Array.isArray(value)) return walkArray(value, state);
62
+ if (!isPlainObject(value)) return value;
63
+
64
+ let changed = false;
65
+ const next: Record<string, unknown> = {};
66
+
67
+ for (const [key, child] of Object.entries(value)) {
68
+ const rewritten =
69
+ key === FIELD_VALUES_KEY && Array.isArray(child)
70
+ ? walkEntries(child, state)
71
+ : walk(child, state);
72
+
73
+ if (rewritten !== child) changed = true;
74
+ next[key] = rewritten;
75
+ }
76
+
77
+ return changed ? next : value;
78
+ }
79
+
80
+ function walkArray(
81
+ values: ReadonlyArray<unknown>,
82
+ state: { rewrote: boolean },
83
+ ): ReadonlyArray<unknown> {
84
+ let changed = false;
85
+ const next = values.map((item) => {
86
+ const rewritten = walk(item, state);
87
+ if (rewritten !== item) changed = true;
88
+ return rewritten;
89
+ });
90
+
91
+ return changed ? next : values;
92
+ }
93
+
94
+ /**
95
+ * Normalize the entries of one `fieldValuesAttributes` array: wrap `content`,
96
+ * and keep walking every sibling key (`linkedRecordAttributes`, nested
97
+ * `fieldValuesAttributes`, …). Deliberately does not descend into `content`
98
+ * itself — that payload is opaque user JSON.
99
+ */
100
+ function walkEntries(
101
+ entries: ReadonlyArray<unknown>,
102
+ state: { rewrote: boolean },
103
+ ): ReadonlyArray<unknown> {
104
+ let arrayChanged = false;
105
+
106
+ const next = entries.map((entry) => {
107
+ if (!isPlainObject(entry)) return entry;
108
+
109
+ let changed = false;
110
+ const rewritten: Record<string, unknown> = {};
111
+
112
+ for (const [key, child] of Object.entries(entry)) {
113
+ const value =
114
+ key === 'content'
115
+ ? normalizeFieldValueContent(child)
116
+ : key === FIELD_VALUES_KEY && Array.isArray(child)
117
+ ? walkEntries(child, state)
118
+ : walk(child, state);
119
+
120
+ if (value !== child) {
121
+ changed = true;
122
+ if (key === 'content') state.rewrote = true;
123
+ }
124
+ rewritten[key] = value;
125
+ }
126
+
127
+ if (!changed) return entry;
128
+ arrayChanged = true;
129
+ return rewritten;
130
+ });
131
+
132
+ return arrayChanged ? next : entries;
133
+ }
134
+
135
+ /**
136
+ * Normalize a standalone `fieldValuesAttributes` array. Exported for callers
137
+ * that assemble one by hand outside an SDK mutation.
138
+ */
139
+ export function normalizeFieldValuesAttributes<T extends FieldValueLike>(
140
+ attributes: ReadonlyArray<T | null | undefined> | null | undefined,
141
+ ): typeof attributes {
142
+ if (!attributes) return attributes;
143
+
144
+ const state = { rewrote: false };
145
+ const normalized = walkEntries(attributes, state) as typeof attributes;
146
+ warnOnce(state);
147
+
148
+ return normalized;
149
+ }
150
+
151
+ /**
152
+ * Normalize every `fieldValuesAttributes` array reachable from a mutation's
153
+ * variables, at any depth. Returns the input untouched — same reference, and
154
+ * same references for every unchanged subtree — when there is nothing to do.
155
+ */
156
+ export function normalizeMutationVariables<V>(variables: V): V {
157
+ if (!isPlainObject(variables) && !Array.isArray(variables)) return variables;
158
+
159
+ const state = { rewrote: false };
160
+ const normalized = walk(variables, state) as V;
161
+ warnOnce(state);
162
+
163
+ return normalized;
164
+ }