easy-airtable-api 0.0.17 → 0.1.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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0
4
+
5
+ - Exported a broader canonical public field/value type surface, including shared types used by generated code such as `AICell`, `BarcodeCell`, `BarcodeWrite`, `ButtonCell`, and `CollaboratorWrite`.
6
+ - Improved code generation to normalize legacy Airtable metadata variants, normalize Unicode identifiers, and emit collision-safe table/field constants and interface properties.
7
+ - Fixed generated typing for `aiText`, lookup/rollup nested collection results, duplicate field names, and response-mode guardrails for field-name-keyed generated record types.
8
+ - Expanded codegen fixture coverage and compile/type-level tests for aliases, Unicode, collisions, generated output safety, and response-mode compatibility.
9
+
3
10
  ## 0.0.17
4
11
 
5
12
  - Reworked Airtable type generation around the new `easy-airtable-api/codegen` workflow.
package/README.md CHANGED
@@ -189,6 +189,42 @@ await generateAirtableTypes({
189
189
  });
190
190
  ```
191
191
 
192
+ ### Generated type assumptions
193
+
194
+ Generated read types target Airtable's default JSON response mode:
195
+
196
+ - `cellFormat: 'json'`
197
+ - `returnFieldsByFieldId: false`
198
+
199
+ If you switch to `cellFormat: 'string'` or `returnFieldsByFieldId: true`, the response shape is no longer compatible with field-name-keyed generated interfaces. The read helpers now include type-level guardrails for this path, and incompatible calls fall back to untyped field maps unless you stay on the default JSON mode.
200
+
201
+ ### Shared field/value types
202
+
203
+ Generated files import shared canonical field/value types from the package root instead of emitting duplicate local interfaces. You can import the same types in application code:
204
+
205
+ ```ts
206
+ import type {
207
+ AICell,
208
+ Attachment,
209
+ AttachmentWrite,
210
+ BarcodeCell,
211
+ BarcodeWrite,
212
+ ButtonCell,
213
+ Collaborator,
214
+ CollaboratorWrite,
215
+ } from 'easy-airtable-api';
216
+ ```
217
+
218
+ Examples:
219
+
220
+ - `aiText` read values use `AICell`
221
+ - attachment reads use `Attachment[]`, writes use `AttachmentWrite[]`
222
+ - collaborator reads use `Collaborator` / `Collaborator[]`, writes use `CollaboratorWrite` / `CollaboratorWrite[]`
223
+ - barcode reads use `BarcodeCell`, writes use `BarcodeWrite`
224
+ - button fields are readonly and use `ButtonCell`
225
+
226
+ These shared types make generated output and application code agree on one canonical public surface. They do not, by themselves, guarantee that every structured write shape has been exhaustively live-verified against Airtable in every edge case.
227
+
192
228
  ## Metadata/base APIs
193
229
 
194
230
  ### List accessible bases
@@ -479,6 +515,12 @@ import {
479
515
  } from 'easy-airtable-api/codegen';
480
516
  ```
481
517
 
518
+ ## Testing
519
+
520
+ Codegen coverage lives in focused fixtures under `tests/fixtures/` and runs as part of the normal Vitest suite.
521
+
522
+ The fixture matrix also includes compile checks for generated output and type-level guardrail tests for response modes that are incompatible with field-name-keyed generated types.
523
+
482
524
  ## Changelog
483
525
 
484
526
  See [CHANGELOG.md](./CHANGELOG.md).
Binary file
@@ -1,26 +1,48 @@
1
- import { quotePropertyKey, toSafeConstKey } from './identifiers.js';
1
+ import { quotePropertyKey } from './identifiers.js';
2
2
  function isPrimaryCreateField(field, primaryFieldId, createRequiredMode) {
3
3
  return (createRequiredMode === 'primaryField' &&
4
4
  field.id === primaryFieldId &&
5
5
  Boolean(field.createType));
6
6
  }
7
- function emitInterface({ name, fields, kind, primaryFieldId, createRequiredMode, }) {
8
- const writableFields = fields.filter((field) => {
9
- if (kind === 'read')
10
- return true;
11
- if (kind === 'create')
12
- return Boolean(field.createType);
13
- return Boolean(field.updateType);
7
+ function getFieldTypeForKind(field, kind) {
8
+ if (kind === 'read')
9
+ return field.readType;
10
+ if (kind === 'create')
11
+ return field.createType;
12
+ return field.updateType;
13
+ }
14
+ function groupFieldsByPropertyKey(fields, kind) {
15
+ const groups = new Map();
16
+ fields.forEach((field) => {
17
+ const type = getFieldTypeForKind(field, kind);
18
+ if (!type)
19
+ return;
20
+ const existing = groups.get(field.tsKey);
21
+ if (existing) {
22
+ existing.push(field);
23
+ return;
24
+ }
25
+ groups.set(field.tsKey, [field]);
14
26
  });
15
- const lines = writableFields.map((field) => {
16
- const type = kind === 'read'
17
- ? field.readType
18
- : kind === 'create'
19
- ? field.createType
20
- : field.updateType;
27
+ return [...groups.entries()].map(([key, groupedFields]) => ({
28
+ key,
29
+ fields: groupedFields,
30
+ }));
31
+ }
32
+ function unionTypes(types) {
33
+ const distinctTypes = [...new Set(types)];
34
+ return distinctTypes.join(' | ');
35
+ }
36
+ function emitInterface({ name, fields, kind, primaryFieldId, createRequiredMode, }) {
37
+ const groupedFields = groupFieldsByPropertyKey(fields, kind);
38
+ const lines = groupedFields.map(({ key, fields: grouped }) => {
39
+ const propertyTypes = grouped
40
+ .map((field) => getFieldTypeForKind(field, kind))
41
+ .filter((type) => Boolean(type));
42
+ const propertyType = unionTypes(propertyTypes);
21
43
  const isRequired = kind === 'create' &&
22
- isPrimaryCreateField(field, primaryFieldId, createRequiredMode);
23
- return ` ${quotePropertyKey(field.tsKey)}${isRequired ? '' : '?'}: ${type};`;
44
+ grouped.some((field) => isPrimaryCreateField(field, primaryFieldId, createRequiredMode));
45
+ return ` ${quotePropertyKey(key)}${isRequired ? '' : '?'}: ${propertyType};`;
24
46
  });
25
47
  if (!lines.length) {
26
48
  return `export interface ${name} {}`;
@@ -33,13 +55,13 @@ function emitEnumAliases(table) {
33
55
  .map((field) => `export type ${field.tsTypeName} = ${field.enumTypeAlias};`);
34
56
  }
35
57
  function emitTableIds(normalizedBase) {
36
- const lines = normalizedBase.tables.map((table) => ` ${toSafeConstKey(table.tsName)}: ${JSON.stringify(table.id)},`);
58
+ const lines = normalizedBase.tables.map((table) => ` ${table.tsConstKey}: ${JSON.stringify(table.id)},`);
37
59
  return ['export const tables = {', ...lines, '} as const;'].join('\n');
38
60
  }
39
61
  function emitFieldIds(normalizedBase) {
40
62
  const lines = normalizedBase.tables.map((table) => {
41
- const fieldLines = table.fields.map((field) => ` ${toSafeConstKey(field.tsKey)}: ${JSON.stringify(field.id)},`);
42
- return [` ${toSafeConstKey(table.tsName)}: {`, ...fieldLines, ' },'].join('\n');
63
+ const fieldLines = table.fields.map((field) => ` ${field.tsConstKey}: ${JSON.stringify(field.id)},`);
64
+ return [` ${table.tsConstKey}: {`, ...fieldLines, ' },'].join('\n');
43
65
  });
44
66
  return ['export const fields = {', ...lines, '} as const;'].join('\n');
45
67
  }
@@ -47,18 +69,9 @@ export function emitTypeScript({ normalizedBase, includeTableIds, includeFieldId
47
69
  const sections = [
48
70
  '/* eslint-disable */',
49
71
  '// Generated by easy-airtable-api. Do not edit manually.',
72
+ "// Generated record-field types assume Airtable's default response mode: cellFormat: 'json' and returnFieldsByFieldId: false.",
50
73
  '',
51
- "import type { AirtableRecord, Attachment, AttachmentWrite, Collaborator } from 'easy-airtable-api';",
52
- '',
53
- 'export interface Barcode {',
54
- ' text: string;',
55
- ' type?: string;',
56
- '}',
57
- '',
58
- 'export interface ButtonFieldValue {',
59
- ' label: string;',
60
- ' url: string | null;',
61
- '}',
74
+ "import type { AICell, AirtableRecord, Attachment, AttachmentWrite, BarcodeCell, BarcodeWrite, ButtonCell, Collaborator, CollaboratorWrite } from 'easy-airtable-api';",
62
75
  ];
63
76
  if (includeTableIds) {
64
77
  sections.push('', emitTableIds(normalizedBase));
@@ -4,4 +4,8 @@ export declare function makeUniquePascalNames<T extends {
4
4
  id: string;
5
5
  name: string;
6
6
  }>(items: T[]): Map<string, string>;
7
+ export declare function makeUniqueConstKeys<T extends {
8
+ id: string;
9
+ name: string;
10
+ }>(items: T[]): Map<string, string>;
7
11
  export declare function quotePropertyKey(value: string): string;
@@ -1,10 +1,14 @@
1
1
  const NON_IDENTIFIER = /[^a-zA-Z0-9_$]+/g;
2
2
  const MULTIPLE_UNDERSCORES = /_+/g;
3
+ const COMBINING_MARKS = /[\u0300-\u036f]/g;
4
+ function normalizeIdentifierInput(value) {
5
+ return value.normalize('NFKD').replace(COMBINING_MARKS, '');
6
+ }
3
7
  function suffixFromId(id) {
4
8
  return id.replace(/[^a-zA-Z0-9]/g, '').slice(-6) || 'Id';
5
9
  }
6
10
  export function toPascalCase(value) {
7
- const normalized = value
11
+ const normalized = normalizeIdentifierInput(value)
8
12
  .replace(NON_IDENTIFIER, ' ')
9
13
  .trim()
10
14
  .split(/\s+/)
@@ -18,7 +22,7 @@ export function toPascalCase(value) {
18
22
  return normalized;
19
23
  }
20
24
  export function toSafeConstKey(value) {
21
- const normalized = value
25
+ const normalized = normalizeIdentifierInput(value)
22
26
  .replace(NON_IDENTIFIER, '_')
23
27
  .replace(MULTIPLE_UNDERSCORES, '_')
24
28
  .replace(/^_+|_+$/g, '');
@@ -46,6 +50,24 @@ export function makeUniquePascalNames(items) {
46
50
  });
47
51
  return result;
48
52
  }
53
+ export function makeUniqueConstKeys(items) {
54
+ const result = new Map();
55
+ const counts = new Map();
56
+ items.forEach((item) => {
57
+ const base = toSafeConstKey(item.name);
58
+ const count = counts.get(base) ?? 0;
59
+ counts.set(base, count + 1);
60
+ });
61
+ items.forEach((item) => {
62
+ const base = toSafeConstKey(item.name);
63
+ if ((counts.get(base) ?? 0) === 1) {
64
+ result.set(item.id, base);
65
+ return;
66
+ }
67
+ result.set(item.id, `${base}_${suffixFromId(item.id)}`);
68
+ });
69
+ return result;
70
+ }
49
71
  export function quotePropertyKey(value) {
50
72
  return JSON.stringify(value);
51
73
  }
@@ -1,31 +1,30 @@
1
1
  import type { AirtableFieldSchema } from '../types/metadata.js';
2
2
  import type { EnumMode, NormalizedField, UnknownFieldBehavior } from './types.js';
3
+ type CollectionKind = 'scalar' | 'array';
4
+ type MappedFieldType = {
5
+ type: string;
6
+ warning?: string;
7
+ collection: CollectionKind;
8
+ };
3
9
  export declare function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }: {
4
10
  field: AirtableFieldSchema;
5
11
  enumMode: EnumMode;
6
12
  unknownFieldBehavior: UnknownFieldBehavior;
7
13
  }): {
8
- read: {
9
- type: string;
10
- warning?: string;
11
- };
12
- create?: {
13
- type: string;
14
- warning?: string;
15
- };
16
- update?: {
17
- type: string;
18
- warning?: string;
19
- };
14
+ read: MappedFieldType;
15
+ create?: MappedFieldType;
16
+ update?: MappedFieldType;
20
17
  readonly: boolean;
21
18
  computed: boolean;
22
19
  linkedTableId?: string;
23
20
  enumTypeAlias?: string;
24
21
  };
25
- export declare function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsTypeName, }: {
22
+ export declare function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsConstKey, tsTypeName, }: {
26
23
  field: AirtableFieldSchema;
27
24
  enumMode: EnumMode;
28
25
  unknownFieldBehavior: UnknownFieldBehavior;
29
26
  tsKey: string;
27
+ tsConstKey: string;
30
28
  tsTypeName: string;
31
29
  }): NormalizedField;
30
+ export {};
@@ -1,4 +1,9 @@
1
1
  import { getChoices, getRecordValue, stringifyUnion } from './utils.js';
2
+ const FIELD_TYPE_ALIASES = {
3
+ attachment: 'multipleAttachments',
4
+ linkToAnotherRecord: 'multipleRecordLinks',
5
+ multipleLookupValues: 'lookup',
6
+ };
2
7
  const READONLY_FIELD_TYPES = new Set([
3
8
  'aiText',
4
9
  'autoNumber',
@@ -23,6 +28,9 @@ const COMPUTED_FIELD_TYPES = new Set([
23
28
  'rollup',
24
29
  'syncSource',
25
30
  ]);
31
+ function canonicalizeFieldType(type) {
32
+ return FIELD_TYPE_ALIASES[type] ?? type;
33
+ }
26
34
  function resolveUnknown(field, unknownFieldBehavior, reason) {
27
35
  const warning = reason
28
36
  ? `${field.name}: ${reason}`
@@ -30,13 +38,18 @@ function resolveUnknown(field, unknownFieldBehavior, reason) {
30
38
  if (unknownFieldBehavior === 'error') {
31
39
  throw new Error(warning);
32
40
  }
33
- return { type: 'unknown', warning };
41
+ return {
42
+ type: 'unknown',
43
+ warning,
44
+ collection: 'scalar',
45
+ };
34
46
  }
35
47
  function resolveUnknownArray(field, unknownFieldBehavior, reason) {
36
48
  const resolved = resolveUnknown(field, unknownFieldBehavior, reason);
37
49
  return {
38
50
  type: 'unknown[]',
39
51
  warning: resolved.warning,
52
+ collection: 'array',
40
53
  };
41
54
  }
42
55
  function buildEnumType(field, enumMode) {
@@ -67,10 +80,12 @@ function mapResultDescriptor(descriptor, field, enumMode, unknownFieldBehavior)
67
80
  }).read;
68
81
  }
69
82
  export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
70
- const readonly = READONLY_FIELD_TYPES.has(field.type);
71
- const computed = COMPUTED_FIELD_TYPES.has(field.type);
72
- const linkedTableId = getRecordValue(field.options, 'linkedTableId');
73
- switch (field.type) {
83
+ const canonicalType = canonicalizeFieldType(field.type);
84
+ const normalizedField = canonicalType === field.type ? field : { ...field, type: canonicalType };
85
+ const readonly = READONLY_FIELD_TYPES.has(canonicalType);
86
+ const computed = COMPUTED_FIELD_TYPES.has(canonicalType);
87
+ const linkedTableId = getRecordValue(normalizedField.options, 'linkedTableId');
88
+ switch (canonicalType) {
74
89
  case 'singleLineText':
75
90
  case 'multilineText':
76
91
  case 'richText':
@@ -80,15 +95,15 @@ export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
80
95
  case 'date':
81
96
  case 'dateTime':
82
97
  return {
83
- read: { type: 'string' },
84
- create: { type: 'string' },
85
- update: { type: 'string' },
98
+ read: { type: 'string', collection: 'scalar' },
99
+ create: { type: 'string', collection: 'scalar' },
100
+ update: { type: 'string', collection: 'scalar' },
86
101
  readonly,
87
102
  computed,
88
103
  };
89
104
  case 'aiText':
90
105
  return {
91
- read: { type: 'string' },
106
+ read: { type: 'AICell', collection: 'scalar' },
92
107
  readonly,
93
108
  computed,
94
109
  };
@@ -98,114 +113,112 @@ export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
98
113
  case 'rating':
99
114
  case 'duration':
100
115
  return {
101
- read: { type: 'number' },
102
- create: { type: 'number' },
103
- update: { type: 'number' },
116
+ read: { type: 'number', collection: 'scalar' },
117
+ create: { type: 'number', collection: 'scalar' },
118
+ update: { type: 'number', collection: 'scalar' },
104
119
  readonly,
105
120
  computed,
106
121
  };
107
122
  case 'checkbox':
108
123
  return {
109
- read: { type: 'boolean' },
110
- create: { type: 'boolean' },
111
- update: { type: 'boolean' },
124
+ read: { type: 'boolean', collection: 'scalar' },
125
+ create: { type: 'boolean', collection: 'scalar' },
126
+ update: { type: 'boolean', collection: 'scalar' },
112
127
  readonly,
113
128
  computed,
114
129
  };
115
130
  case 'singleSelect': {
116
- const enumType = buildEnumType(field, enumMode) ?? 'string';
131
+ const enumType = buildEnumType(normalizedField, enumMode) ?? 'string';
117
132
  return {
118
- read: { type: enumType },
119
- create: { type: enumType },
120
- update: { type: enumType },
133
+ read: { type: enumType, collection: 'scalar' },
134
+ create: { type: enumType, collection: 'scalar' },
135
+ update: { type: enumType, collection: 'scalar' },
121
136
  readonly,
122
137
  computed,
123
138
  enumTypeAlias: enumType,
124
139
  };
125
140
  }
126
141
  case 'multipleSelects': {
127
- const enumType = buildEnumType(field, enumMode) ?? 'string';
142
+ const enumType = buildEnumType(normalizedField, enumMode) ?? 'string';
128
143
  return {
129
- read: { type: `Array<${enumType}>` },
130
- create: { type: `Array<${enumType}>` },
131
- update: { type: `Array<${enumType}>` },
144
+ read: { type: `Array<${enumType}>`, collection: 'array' },
145
+ create: { type: `Array<${enumType}>`, collection: 'array' },
146
+ update: { type: `Array<${enumType}>`, collection: 'array' },
132
147
  readonly,
133
148
  computed,
134
149
  enumTypeAlias: enumType,
135
150
  };
136
151
  }
137
152
  case 'multipleAttachments':
138
- case 'attachment':
139
153
  return {
140
- read: { type: 'Attachment[]' },
141
- create: { type: 'AttachmentWrite[]' },
142
- update: { type: 'AttachmentWrite[]' },
154
+ read: { type: 'Attachment[]', collection: 'array' },
155
+ create: { type: 'AttachmentWrite[]', collection: 'array' },
156
+ update: { type: 'AttachmentWrite[]', collection: 'array' },
143
157
  readonly,
144
158
  computed,
145
159
  };
146
160
  case 'singleCollaborator':
147
161
  return {
148
- read: { type: 'Collaborator' },
149
- create: { type: 'Collaborator' },
150
- update: { type: 'Collaborator' },
162
+ read: { type: 'Collaborator', collection: 'scalar' },
163
+ create: { type: 'CollaboratorWrite', collection: 'scalar' },
164
+ update: { type: 'CollaboratorWrite', collection: 'scalar' },
151
165
  readonly,
152
166
  computed,
153
167
  };
154
168
  case 'multipleCollaborators':
155
169
  return {
156
- read: { type: 'Collaborator[]' },
157
- create: { type: 'Collaborator[]' },
158
- update: { type: 'Collaborator[]' },
170
+ read: { type: 'Collaborator[]', collection: 'array' },
171
+ create: { type: 'CollaboratorWrite[]', collection: 'array' },
172
+ update: { type: 'CollaboratorWrite[]', collection: 'array' },
159
173
  readonly,
160
174
  computed,
161
175
  };
162
176
  case 'multipleRecordLinks':
163
- case 'linkToAnotherRecord':
164
177
  return {
165
- read: { type: 'string[]' },
166
- create: { type: 'string[]' },
167
- update: { type: 'string[]' },
178
+ read: { type: 'string[]', collection: 'array' },
179
+ create: { type: 'string[]', collection: 'array' },
180
+ update: { type: 'string[]', collection: 'array' },
168
181
  readonly,
169
182
  computed,
170
183
  linkedTableId,
171
184
  };
172
185
  case 'barcode':
173
186
  return {
174
- read: { type: 'Barcode' },
175
- create: { type: 'Barcode' },
176
- update: { type: 'Barcode' },
187
+ read: { type: 'BarcodeCell', collection: 'scalar' },
188
+ create: { type: 'BarcodeWrite', collection: 'scalar' },
189
+ update: { type: 'BarcodeWrite', collection: 'scalar' },
177
190
  readonly,
178
191
  computed,
179
192
  };
180
193
  case 'createdTime':
181
194
  case 'lastModifiedTime':
182
195
  return {
183
- read: { type: 'string' },
196
+ read: { type: 'string', collection: 'scalar' },
184
197
  readonly,
185
198
  computed,
186
199
  };
187
200
  case 'createdBy':
188
201
  case 'lastModifiedBy':
189
202
  return {
190
- read: { type: 'Collaborator' },
203
+ read: { type: 'Collaborator', collection: 'scalar' },
191
204
  readonly,
192
205
  computed,
193
206
  };
194
207
  case 'button':
195
208
  return {
196
- read: { type: 'ButtonFieldValue' },
209
+ read: { type: 'ButtonCell', collection: 'scalar' },
197
210
  readonly,
198
211
  computed,
199
212
  };
200
213
  case 'count':
201
214
  case 'autoNumber':
202
215
  return {
203
- read: { type: 'number' },
216
+ read: { type: 'number', collection: 'scalar' },
204
217
  readonly,
205
218
  computed,
206
219
  };
207
220
  case 'formula': {
208
- const result = mapResultDescriptor(getRecordValue(field.options, 'result'), field, enumMode, unknownFieldBehavior);
221
+ const result = mapResultDescriptor(getRecordValue(normalizedField.options, 'result'), normalizedField, enumMode, unknownFieldBehavior);
209
222
  return {
210
223
  read: result,
211
224
  readonly,
@@ -213,10 +226,10 @@ export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
213
226
  };
214
227
  }
215
228
  case 'rollup': {
216
- const result = getRecordValue(field.options, 'result');
229
+ const result = getRecordValue(normalizedField.options, 'result');
217
230
  const mapped = result
218
- ? mapResultDescriptor(result, field, enumMode, unknownFieldBehavior)
219
- : resolveUnknown(field, unknownFieldBehavior, 'rollup result metadata is missing');
231
+ ? mapResultDescriptor(result, normalizedField, enumMode, unknownFieldBehavior)
232
+ : resolveUnknown(normalizedField, unknownFieldBehavior, 'rollup result metadata is missing');
220
233
  return {
221
234
  read: mapped,
222
235
  readonly,
@@ -224,20 +237,24 @@ export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
224
237
  };
225
238
  }
226
239
  case 'lookup': {
227
- const result = getRecordValue(field.options, 'result');
240
+ const result = getRecordValue(normalizedField.options, 'result');
228
241
  const mapped = result
229
- ? mapResultDescriptor(result, field, enumMode, unknownFieldBehavior)
230
- : resolveUnknownArray(field, unknownFieldBehavior, 'lookup result metadata is missing');
242
+ ? mapResultDescriptor(result, normalizedField, enumMode, unknownFieldBehavior)
243
+ : resolveUnknownArray(normalizedField, unknownFieldBehavior, 'lookup result metadata is missing');
231
244
  return {
232
- read: mapped.type === 'unknown'
233
- ? { ...mapped, type: 'unknown[]' }
234
- : { ...mapped, type: `Array<${mapped.type}>` },
245
+ read: mapped.collection === 'array'
246
+ ? mapped
247
+ : {
248
+ ...mapped,
249
+ type: mapped.type === 'unknown' ? 'unknown[]' : `Array<${mapped.type}>`,
250
+ collection: 'array',
251
+ },
235
252
  readonly,
236
253
  computed,
237
254
  };
238
255
  }
239
256
  default: {
240
- const unknown = resolveUnknown(field, unknownFieldBehavior);
257
+ const unknown = resolveUnknown(normalizedField, unknownFieldBehavior);
241
258
  return {
242
259
  read: unknown,
243
260
  create: readonly ? undefined : unknown,
@@ -248,7 +265,7 @@ export function mapFieldTypes({ field, enumMode, unknownFieldBehavior, }) {
248
265
  }
249
266
  }
250
267
  }
251
- export function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsTypeName, }) {
268
+ export function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavior, tsKey, tsConstKey, tsTypeName, }) {
252
269
  const mapped = mapFieldTypes({
253
270
  field,
254
271
  enumMode,
@@ -263,6 +280,7 @@ export function mapFieldToNormalizedField({ field, enumMode, unknownFieldBehavio
263
280
  id: field.id,
264
281
  name: field.name,
265
282
  tsKey,
283
+ tsConstKey,
266
284
  tsTypeName,
267
285
  airtableType: field.type,
268
286
  readonly: mapped.readonly,
@@ -1,6 +1,14 @@
1
- import { makeUniquePascalNames, toPascalCase } from './identifiers.js';
1
+ import { makeUniqueConstKeys, makeUniquePascalNames, toPascalCase, toSafeConstKey, } from './identifiers.js';
2
2
  import { mapFieldToNormalizedField } from './map-field.js';
3
3
  import { compareByNameThenId, ensureArray } from './utils.js';
4
+ function countBy(items, getKey) {
5
+ const counts = new Map();
6
+ items.forEach((item) => {
7
+ const key = getKey(item);
8
+ counts.set(key, (counts.get(key) ?? 0) + 1);
9
+ });
10
+ return counts;
11
+ }
4
12
  export function normalizeSchema({ schema, tableNameOrId, enumMode, unknownFieldBehavior, }) {
5
13
  const filters = new Set(ensureArray(tableNameOrId));
6
14
  const selectedTables = [...schema.tables]
@@ -15,34 +23,43 @@ export function normalizeSchema({ schema, tableNameOrId, enumMode, unknownFieldB
15
23
  }
16
24
  const warnings = [];
17
25
  const tableNames = makeUniquePascalNames(selectedTables);
18
- const sanitizedTableNameCounts = new Map();
19
- selectedTables.forEach((table) => {
20
- const baseName = toPascalCase(table.name);
21
- sanitizedTableNameCounts.set(baseName, (sanitizedTableNameCounts.get(baseName) ?? 0) + 1);
22
- });
26
+ const tableConstKeys = makeUniqueConstKeys(selectedTables);
27
+ const tableTypeNameCounts = countBy(selectedTables, (table) => toPascalCase(table.name));
28
+ const tableConstKeyCounts = countBy(selectedTables, (table) => toSafeConstKey(table.name));
23
29
  const tables = selectedTables.map((table) => {
24
30
  const tsName = tableNames.get(table.id) ?? table.name;
25
- if ((sanitizedTableNameCounts.get(toPascalCase(table.name)) ?? 0) > 1) {
31
+ const tsConstKey = tableConstKeys.get(table.id) ?? table.name;
32
+ if ((tableTypeNameCounts.get(toPascalCase(table.name)) ?? 0) > 1) {
26
33
  warnings.push(`Table name collision detected for ${table.name}. Generated type name ${tsName} includes a stable suffix.`);
27
34
  }
35
+ if ((tableConstKeyCounts.get(toSafeConstKey(table.name)) ?? 0) > 1) {
36
+ warnings.push(`Table const key collision detected for ${table.name}. Generated tables key ${tsConstKey} includes a stable suffix.`);
37
+ }
28
38
  const fieldNames = makeUniquePascalNames(table.fields);
29
- const sanitizedFieldNameCounts = new Map();
30
- table.fields.forEach((field) => {
31
- const baseName = toPascalCase(field.name);
32
- sanitizedFieldNameCounts.set(baseName, (sanitizedFieldNameCounts.get(baseName) ?? 0) + 1);
33
- });
39
+ const fieldConstKeys = makeUniqueConstKeys(table.fields);
40
+ const exactFieldNameCounts = countBy(table.fields, (field) => field.name);
41
+ const fieldTypeNameCounts = countBy(table.fields, (field) => toPascalCase(field.name));
42
+ const fieldConstKeyCounts = countBy(table.fields, (field) => toSafeConstKey(field.name));
34
43
  const fields = table.fields.map((field) => {
35
44
  const fieldTsName = fieldNames.get(field.id) ?? field.name;
45
+ const fieldTsConstKey = fieldConstKeys.get(field.id) ?? field.name;
36
46
  const normalizedField = mapFieldToNormalizedField({
37
47
  field,
38
48
  enumMode,
39
49
  unknownFieldBehavior,
40
50
  tsKey: field.name,
51
+ tsConstKey: fieldTsConstKey,
41
52
  tsTypeName: `${tsName}${fieldTsName}`,
42
53
  });
43
- if ((sanitizedFieldNameCounts.get(toPascalCase(field.name)) ?? 0) > 1) {
54
+ if ((exactFieldNameCounts.get(field.name) ?? 0) > 1) {
55
+ warnings.push(`Duplicate field name detected for ${table.name}.${field.name}. Generated interfaces merge the colliding fields into a union.`);
56
+ }
57
+ if ((fieldTypeNameCounts.get(toPascalCase(field.name)) ?? 0) > 1) {
44
58
  warnings.push(`Field name collision detected for ${table.name}.${field.name}. Generated helper type name ${normalizedField.tsTypeName} includes a stable suffix.`);
45
59
  }
60
+ if ((fieldConstKeyCounts.get(toSafeConstKey(field.name)) ?? 0) > 1) {
61
+ warnings.push(`Field const key collision detected for ${table.name}.${field.name}. Generated fields key ${normalizedField.tsConstKey} includes a stable suffix.`);
62
+ }
46
63
  warnings.push(...normalizedField.warnings.map((warning) => `${table.name}.${warning}`));
47
64
  return normalizedField;
48
65
  });
@@ -50,6 +67,7 @@ export function normalizeSchema({ schema, tableNameOrId, enumMode, unknownFieldB
50
67
  id: table.id,
51
68
  name: table.name,
52
69
  tsName,
70
+ tsConstKey,
53
71
  primaryFieldId: table.primaryFieldId,
54
72
  fields,
55
73
  };
@@ -41,6 +41,7 @@ export interface NormalizedTable {
41
41
  id: string;
42
42
  name: string;
43
43
  tsName: string;
44
+ tsConstKey: string;
44
45
  primaryFieldId: string;
45
46
  fields: NormalizedField[];
46
47
  }
@@ -48,6 +49,7 @@ export interface NormalizedField {
48
49
  id: string;
49
50
  name: string;
50
51
  tsKey: string;
52
+ tsConstKey: string;
51
53
  tsTypeName: string;
52
54
  airtableType: string;
53
55
  readonly: boolean;
package/lib/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { getRecord, getRecordsPage, iterateRecordsPages, getRecords, createRecor
2
2
  export { listBases, createBase, getBaseSchema } from './bases.js';
3
3
  export { airtableRequestRaw, AirtableApiError } from './requests.js';
4
4
  export type { AirtableRetryOptions } from './requests.js';
5
- export type { AirtableRecord } from './types/records.js';
5
+ export type { AirtableRecord, GeneratedRecordFieldsCompatibleGetRecordOptions, GeneratedRecordFieldsCompatibleGetRecordsOptions, } from './types/records.js';
6
6
  export type { CreateBaseFieldConfig, CreateBaseRequestBody, CreateBaseResponse, CreateBaseTableConfig, ListBasesResponse, } from './types/bases.js';
7
7
  export type { AirtableBaseSchema, AirtableFieldSchema, AirtableTableSchema, AirtableViewSchema, } from './types/metadata.js';
8
- export type { Attachment, AttachmentWrite, Collaborator, } from './types/fields.js';
8
+ export type { AICell, Attachment, AttachmentWrite, Barcode, BarcodeCell, BarcodeWrite, ButtonCell, ButtonFieldValue, Collaborator, CollaboratorWrite, } from './types/fields.js';
package/lib/records.d.ts CHANGED
@@ -1,40 +1,75 @@
1
- import { AirtableRecord, DeleteRecordResponse, DeleteRecordsResponse, GetRecordQueryParameters, GetRecordsQueryParameters } from './types/records.js';
1
+ import { AirtableRecord, DeleteRecordResponse, DeleteRecordsResponse, GeneratedRecordFieldsCompatibleGetRecordOptions, GeneratedRecordFieldsCompatibleGetRecordsOptions, GetRecordQueryParameters, GetRecordsQueryParameters } from './types/records.js';
2
2
  import type { AirtableRetryOptions } from './requests.js';
3
3
  export declare function getRecord<Fields>({ apiKey, baseId, tableId, recordId, options, retry, }: {
4
4
  apiKey: string;
5
5
  baseId: string;
6
6
  tableId: string;
7
7
  recordId: string;
8
- options?: GetRecordQueryParameters;
8
+ options?: GeneratedRecordFieldsCompatibleGetRecordOptions;
9
9
  retry?: AirtableRetryOptions;
10
10
  }): Promise<AirtableRecord<Fields>>;
11
+ export declare function getRecord({ apiKey, baseId, tableId, recordId, options, retry, }: {
12
+ apiKey: string;
13
+ baseId: string;
14
+ tableId: string;
15
+ recordId: string;
16
+ options?: GetRecordQueryParameters;
17
+ retry?: AirtableRetryOptions;
18
+ }): Promise<AirtableRecord<Record<string, unknown>>>;
11
19
  export declare function getRecordsPage<Fields>({ apiKey, baseId, tableId, options, retry, }: {
12
20
  apiKey: string;
13
21
  baseId: string;
14
22
  tableId: string;
15
- options?: GetRecordsQueryParameters;
23
+ options?: GeneratedRecordFieldsCompatibleGetRecordsOptions;
16
24
  retry?: AirtableRetryOptions;
17
25
  }): Promise<{
18
26
  records: AirtableRecord<Fields>[];
19
27
  offset?: string;
20
28
  }>;
21
- export declare function iterateRecordsPages<Fields>({ apiKey, baseId, tableId, options, retry, }: {
29
+ export declare function getRecordsPage({ apiKey, baseId, tableId, options, retry, }: {
22
30
  apiKey: string;
23
31
  baseId: string;
24
32
  tableId: string;
25
33
  options?: GetRecordsQueryParameters;
26
34
  retry?: AirtableRetryOptions;
35
+ }): Promise<{
36
+ records: AirtableRecord<Record<string, unknown>>[];
37
+ offset?: string;
38
+ }>;
39
+ export declare function iterateRecordsPages<Fields>({ apiKey, baseId, tableId, options, retry, }: {
40
+ apiKey: string;
41
+ baseId: string;
42
+ tableId: string;
43
+ options?: GeneratedRecordFieldsCompatibleGetRecordsOptions;
44
+ retry?: AirtableRetryOptions;
27
45
  }): AsyncGenerator<{
28
46
  records: AirtableRecord<Fields>[];
29
47
  offset?: string;
30
48
  }>;
31
- export declare function getRecords<Fields>({ apiKey, baseId, tableId, options, retry, }: {
49
+ export declare function iterateRecordsPages({ apiKey, baseId, tableId, options, retry, }: {
32
50
  apiKey: string;
33
51
  baseId: string;
34
52
  tableId: string;
35
53
  options?: GetRecordsQueryParameters;
36
54
  retry?: AirtableRetryOptions;
55
+ }): AsyncGenerator<{
56
+ records: AirtableRecord<Record<string, unknown>>[];
57
+ offset?: string;
58
+ }>;
59
+ export declare function getRecords<Fields>({ apiKey, baseId, tableId, options, retry, }: {
60
+ apiKey: string;
61
+ baseId: string;
62
+ tableId: string;
63
+ options?: GeneratedRecordFieldsCompatibleGetRecordsOptions;
64
+ retry?: AirtableRetryOptions;
37
65
  }): Promise<AirtableRecord<Fields>[]>;
66
+ export declare function getRecords({ apiKey, baseId, tableId, options, retry, }: {
67
+ apiKey: string;
68
+ baseId: string;
69
+ tableId: string;
70
+ options?: GetRecordsQueryParameters;
71
+ retry?: AirtableRetryOptions;
72
+ }): Promise<AirtableRecord<Record<string, unknown>>[]>;
38
73
  export declare function updateRecord<Fields>({ apiKey, baseId, tableId, recordId, fields, options, retry, }: {
39
74
  apiKey: string;
40
75
  baseId: string;
package/lib/records.js CHANGED
@@ -32,13 +32,13 @@ export async function* iterateRecordsPages({ apiKey, baseId, tableId, options, r
32
32
  const requestBody = currentOffset
33
33
  ? { ...options, offset: currentOffset }
34
34
  : options;
35
- const response = await getRecordsPage({
35
+ const response = (await getRecordsPage({
36
36
  apiKey,
37
37
  baseId,
38
38
  tableId,
39
39
  options: requestBody,
40
40
  retry,
41
- });
41
+ }));
42
42
  yield response;
43
43
  currentOffset = response.offset;
44
44
  if (currentOffset && (options?.maxRecords ?? 100) > 100) {
@@ -35,6 +35,11 @@ export interface BarcodeCell {
35
35
  type?: string;
36
36
  text: string;
37
37
  }
38
+ export interface BarcodeWrite {
39
+ text: string;
40
+ type?: string;
41
+ }
42
+ export type Barcode = BarcodeCell;
38
43
  export interface BarcodeFieldTypeAndOptions {
39
44
  type: 'barcode';
40
45
  }
@@ -42,6 +47,7 @@ export interface ButtonCell {
42
47
  label: string;
43
48
  url: string | null;
44
49
  }
50
+ export type ButtonFieldValue = ButtonCell;
45
51
  export interface ButtonFieldTypeAndOptions {
46
52
  type: 'button';
47
53
  }
@@ -60,6 +66,10 @@ export interface CollaboratorCell {
60
66
  name?: string;
61
67
  profilePicUrl?: string;
62
68
  }
69
+ export interface CollaboratorWrite {
70
+ id: string;
71
+ email?: string;
72
+ }
63
73
  export interface SingleCollaboratorFieldTypeAndOptions {
64
74
  type: 'singleCollaborator';
65
75
  options: Record<string, never>;
@@ -189,12 +199,7 @@ export interface LookupFieldTypeAndOptions {
189
199
  result: unknown;
190
200
  };
191
201
  }
192
- export type Collaborator = {
193
- id: string;
194
- email?: string;
195
- name?: string;
196
- profilePicUrl?: string;
197
- };
202
+ export type Collaborator = CollaboratorCell;
198
203
  export type Collaborators = Collaborator[];
199
204
  export type ChoiceColor = 'blueLight2' | 'cyanLight2' | 'tealLight2' | 'greenLight2' | 'yellowLight2' | 'orangeLight2' | 'redLight2' | 'pinkLight2' | 'purpleLight2' | 'grayLight2' | 'blueLight1' | 'cyanLight1' | 'tealLight1' | 'greenLight1' | 'yellowLight1' | 'orangeLight1' | 'redLight1' | 'pinkLight1' | 'purpleLight1' | 'grayLight1' | 'blueBright' | 'cyanBright' | 'tealBright' | 'greenBright' | 'yellowBright' | 'orangeBright' | 'redBright' | 'pinkBright' | 'purpleBright' | 'grayBright' | 'blueDark1' | 'cyanDark1' | 'tealDark1' | 'greenDark1' | 'yellowDark1' | 'orangeDark1' | 'redDark1' | 'pinkDark1' | 'purpleDark1' | 'grayDark1';
200
205
  export type Choice = {
@@ -245,10 +250,7 @@ export type MultipleAttachments = Attachment[];
245
250
  export type FormulaSingleReturn = string | number;
246
251
  export type Rollup = string | number;
247
252
  export type AutoNumber = number;
248
- export type AirtableButton = {
249
- label: string;
250
- url: string;
251
- };
253
+ export type AirtableButton = ButtonCell;
252
254
  export type LastModifiedTime = string;
253
255
  export type CreatedTime = string;
254
256
  export type DateTime = string;
@@ -30,6 +30,10 @@ export interface GetRecordsQueryParameters {
30
30
  recordMetadata?: RecordMetadataOptions[];
31
31
  requestInterval?: number;
32
32
  }
33
+ export type GeneratedRecordFieldsCompatibleGetRecordsOptions = Omit<GetRecordsQueryParameters, 'cellFormat' | 'returnFieldsByFieldId'> & {
34
+ cellFormat?: 'json';
35
+ returnFieldsByFieldId?: false;
36
+ };
33
37
  type RecordField = {
34
38
  [key: string]: unknown;
35
39
  };
@@ -46,6 +50,10 @@ export interface GetRecordQueryParameters {
46
50
  cellFormat?: CellFormat;
47
51
  returnFieldsByFieldId?: boolean;
48
52
  }
53
+ export type GeneratedRecordFieldsCompatibleGetRecordOptions = Omit<GetRecordQueryParameters, 'cellFormat' | 'returnFieldsByFieldId'> & {
54
+ cellFormat?: 'json';
55
+ returnFieldsByFieldId?: false;
56
+ };
49
57
  export interface GetRecordPathParameters {
50
58
  baseId: BaseId;
51
59
  tableIdOrName: TableIdOrName;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-airtable-api",
3
- "version": "0.0.17",
3
+ "version": "0.1.0",
4
4
  "type": "module",
5
5
  "description": "Lightweight TypeScript-first Airtable client with metadata-based type generation.",
6
6
  "main": "lib/index.js",
@@ -67,4 +67,4 @@
67
67
  "typescript": "^5.4.3",
68
68
  "vitest": "^1.4.0"
69
69
  }
70
- }
70
+ }
Binary file