forked from Adamantine-guild/guildpass-integrations
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-api-types.js
More file actions
413 lines (368 loc) · 13 KB
/
Copy pathsync-api-types.js
File metadata and controls
413 lines (368 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
const fs = require('fs');
const path = require('path');
const SCHEMA_PATH = path.join(__dirname, '../test/fixtures/openapi.json');
const TARGET_PATH = path.join(__dirname, '../lib/api/types.ts');
const STATIC_SUFFIX = `
export type WebhookEventStatus = 'success' | 'failed' | 'pending';
export type WebhookEventType =
| 'membership.created'
| 'membership.renewed'
| 'membership.expired'
| 'tier.upgraded'
| 'policy.updated';
export interface WebhookEventLog {
id: string;
eventType: WebhookEventType;
status: WebhookEventStatus;
timestamp: string;
affectedIdentifier: string; // Wallet address or Resource ID
payloadSummary: {
network?: string;
txHash?: string;
tier?: string;
reason?: string;
};
}
export interface WalletVerification {
verified: boolean
method?: string
checkedAt: string
}
export interface ApiErrorBody {
code?: string
error?: string
message?: string
details?: Record<string, unknown>
}
// ── Access Decision (cached per wallet + resource) ───────────────────────────
/**
* Result of an access check for a specific resource.
* This is the value stored in the route-level access cache.
* Only safe display metadata is included — never sensitive tokens.
*/
export interface AccessDecision {
/** Whether access is granted */
allowed: boolean
/** Human-readable reason for the decision (safe for display) */
reason: string
/** ISO timestamp of when the check was performed */
checkedAt: string
}
// ── Client-side State Types ──────────────────────────────────────────────────
/**
* Distinct states of the admin authentication session.
*
* - disconnected — no wallet connected
* - connected — wallet connected, but SIWE sign-in not yet performed
* - authenticating — SIWE signing flow is in-flight
* - authenticated — valid, non-expired session token is held
* - expired — a session was held but the token has since expired (or
* the backend rejected it with 401); re-auth is required
*/
export type AdminSessionStatus =
| 'disconnected'
| 'connected'
| 'authenticating'
| 'authenticated'
| 'expired'
/**
* Union of authenticated / unauthenticated states for the SIWE context.
*/
export type SiweAuthState =
| SiweAuthSession
| { isAuthenticated: false }
// ── Backend raw types (guildpass-core response shapes) ───────────────────────
// These are the shapes returned by /v1/* endpoints. The live API client maps
// them into the frontend types above. Fields are optional because backend
// versions may use snake_case or camelCase, and this mapping handles both.
export interface BackendMember {
address?: string
wallet_address?: string
tier?: MembershipTier
membership_tier?: MembershipTier
active?: boolean
is_active?: boolean
expiresAt?: string
expires_at?: string
roles?: Role[]
// Profile fields (returned by /v1/members/:address/profile)
displayName?: string
display_name?: string
username?: string
bio?: string
badges?: string[]
}
export interface BackendResource {
id: string
title?: string
name?: string
description?: string
minTier?: MembershipTier
min_tier?: MembershipTier
roles?: Role[]
content?: ResourceContentBlock[]
}
export interface BackendPolicy {
resourceId?: string
resource_id?: string
minTier?: MembershipTier
min_tier?: MembershipTier
roles?: Role[]
rule?: AccessRule
}
export interface BackendSession {
address?: string
wallet_address?: string
roles?: Role[]
membership?: Partial<BackendMember>
community?: {
id: string
name: string
description?: string
tiers?: MembershipTier[]
}
}
// ── API Interface ─────────────────────────────────────────────────────────────
/**
* Read-only member and resource queries.
* No SIWE token is required for these operations.
*/
export interface MemberAccessApi {
// ── Read-only (no auth token required) ──────────────────────────────────
getSession(): Promise<Session>
getCommunity(): Promise<Community>
getMembership(address: string): Promise<Membership | null>
verifyWallet(address: string): Promise<WalletVerification>
getProfile(address: string): Promise<MemberProfile | null>
listMembers(): Promise<MemberRow[]>
listResources(): Promise<Resource[]>
listPolicies(): Promise<AccessPolicy[]>
getResource(id: string): Promise<Resource | null>
getPolicy(resourceId: string): Promise<AccessPolicy | null>
}
/**
* Authenticated admin queries and mutations.
* These methods require a valid SIWE token context.
*/
export interface AdminAccessApi {
// ── Admin queries & mutations (require a valid SIWE token context) ────────
listWebhookEvents(): Promise<WebhookEventLog[]>
assignRole(address: string, role: Role): Promise<void>
removeRole(address: string, role: Role): Promise<void>
updatePolicy(policy: AccessPolicy): Promise<void>
}
/**
* SIWE authentication endpoints.
*/
export interface SiweAuthApi {
// ── SIWE authentication endpoints ────────────────────────────────────────
/** Fetch a one-time nonce for the given address to include in the SIWE message. */
getNonce(address: string): Promise<string>
/**
* Submit a signed EIP-4361 message and receive an authenticated session
* token. The backend verifies the signature and returns a short-lived token.
*/
siweVerify(message: string, signature: string): Promise<SiweAuthSession>
/** Invalidate the current server-side session (no-op for stateless JWTs). */
siweLogout(token: string): Promise<void>
verifyWallet(address: string): Promise<WalletVerification>
}
/**
* Composed client-side API contract.
*
* Built from {@link MemberAccessApi}, {@link AdminAccessApi}, and
* {@link SiweAuthApi} so each surface has a single, unambiguous responsibility
* and implementations cannot drift between duplicated declarations.
*/
export type AccessApi = MemberAccessApi & AdminAccessApi & SiweAuthApi
`;
function getTsType(propSchema) {
if (propSchema.$ref) {
return propSchema.$ref.split('/').pop();
}
if (propSchema.enum) {
return propSchema.enum
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(' | ');
}
if (propSchema.additionalProperties) {
return 'Record<string, unknown>';
}
switch (propSchema.type) {
case 'string':
return 'string';
case 'boolean':
return 'boolean';
case 'integer':
case 'number':
return 'number';
case 'array':
return `${getTsType(propSchema.items)}[]`;
case 'object':
if (propSchema.properties) {
const props = Object.entries(propSchema.properties).map(([name, schema]) => {
const isRequired =
propSchema.required && propSchema.required.includes(name);
return `${name}${isRequired ? '' : '?'}: ${getTsType(schema)}`;
});
return `{ ${props.join('; ')} }`;
}
return 'Record<string, unknown>';
default:
if (propSchema.type !== undefined) {
throw new Error(`Unsupported OpenAPI schema type: ${propSchema.type}`);
}
return 'any';
}
}
function getZodType(propSchema) {
if (propSchema.$ref) {
const refName = propSchema.$ref.split('/').pop();
return `${refName}Schema`;
}
if (propSchema.enum) {
if (propSchema.enum.length === 1 && propSchema.enum[0] === true) {
return `z.literal(true)`;
}
const vals = propSchema.enum
.map((val) => (typeof val === 'string' ? `'${val}'` : val))
.join(', ');
return `z.enum([${vals}])`;
}
if (propSchema.additionalProperties) {
return 'z.record(z.unknown())';
}
switch (propSchema.type) {
case 'string':
return 'z.string()';
case 'boolean':
return 'z.boolean()';
case 'integer':
case 'number':
return 'z.number()';
case 'array':
return `z.array(${getZodType(propSchema.items)})`;
case 'object':
if (propSchema.properties) {
const props = Object.entries(propSchema.properties).map(([name, schema]) => {
const isRequired =
propSchema.required && propSchema.required.includes(name);
const zType = getZodType(schema);
return `${name}: ${zType}${isRequired ? '' : '.optional()'}`;
});
return `z.object({ ${props.join(', ')} })`;
}
return 'z.record(z.unknown())';
default:
return 'z.any()';
}
}
// Schemas whose canonical definition lives in STATIC_SUFFIX rather than openapi.json.
const STATIC_SCHEMA_NAMES = new Set([
'ApiErrorBody',
'WalletVerification',
'WebhookEventLog',
'WebhookEventStatus',
'WebhookEventType',
'WebhookPayloadSummary',
]);
function generateTypes(schema) {
if (!schema) {
const rawSchema = fs.readFileSync(SCHEMA_PATH, 'utf8');
schema = JSON.parse(rawSchema);
}
const schemasObj = schema.components.schemas;
let output = `/**
* This file was auto-generated from the OpenAPI schema.
* DO NOT EDIT THIS FILE DIRECTLY.
* To update these types, edit test/fixtures/openapi.json and run:
* npm run sync-types
*/
import { z } from 'zod';
`;
for (const [schemaName, schemaVal] of Object.entries(schemasObj)) {
if (!STATIC_SCHEMA_NAMES.has(schemaName)) {
if (schemaVal.enum) {
const enumVals = schemaVal.enum
.map((v) => (typeof v === 'string' ? `'${v}'` : v))
.join(' | ');
output += `export type ${schemaName} = ${enumVals}\n\n`;
} else if (schemaVal.oneOf) {
const variants = schemaVal.oneOf.map((variant) => getTsType(variant));
output += `export type ${schemaName} =\n | ${variants.join('\n | ')}\n\n`;
} else if (schemaVal.type === 'object') {
output += `export interface ${schemaName} {\n`;
const props = schemaVal.properties || {};
for (const [propName, propVal] of Object.entries(props)) {
const isRequired =
schemaVal.required && schemaVal.required.includes(propName);
const tsType = getTsType(propVal);
output += ` ${propName}${isRequired ? '' : '?'}: ${tsType}\n`;
}
output += `}\n\n`;
}
}
if (schemaVal.enum) {
if (schemaVal.enum.length === 1 && schemaVal.enum[0] === true) {
output += `export const ${schemaName}Schema = z.literal(true)\n\n`;
} else {
const enumVals = schemaVal.enum
.map((v) => (typeof v === 'string' ? `'${v}'` : v))
.join(', ');
output += `export const ${schemaName}Schema = z.enum([${enumVals}])\n\n`;
}
} else if (schemaVal.oneOf) {
// z.lazy so union schemas may reference themselves recursively (e.g.
// AccessRule's and/or variants contain nested AccessRule arrays).
const variants = schemaVal.oneOf.map((variant) => getZodType(variant));
output += `export const ${schemaName}Schema: z.ZodType<${schemaName}> = z.lazy(() =>\n z.union([\n ${variants.join(',\n ')},\n ]),\n)\n\n`;
} else if (schemaVal.type === 'object') {
output += `export const ${schemaName}Schema = z.object({\n`;
const props = schemaVal.properties || {};
for (const [propName, propVal] of Object.entries(props)) {
const isRequired =
schemaVal.required && schemaVal.required.includes(propName);
const zType = getZodType(propVal);
output += ` ${propName}: ${zType}${isRequired ? '' : '.optional()'},\n`;
}
output += `})\n\n`;
}
}
output += STATIC_SUFFIX.trim() + '\n';
return output;
}
function main() {
const args = process.argv.slice(2);
const isCheck = args.includes('--check');
const isWrite = args.includes('--write');
if (!isCheck && !isWrite) {
console.error('Usage: node scripts/sync-api-types.js [--write | --check]');
process.exit(1);
}
const generated = generateTypes();
if (isCheck) {
if (!fs.existsSync(TARGET_PATH)) {
console.error(`Error: Target file ${TARGET_PATH} does not exist.`);
process.exit(1);
}
const current = fs.readFileSync(TARGET_PATH, 'utf8');
const normGen = generated.replace(/\r\n/g, '\n').trim();
const normCur = current.replace(/\r\n/g, '\n').trim();
if (normGen !== normCur) {
console.error('FAIL: Type drift detected! Frontend API types do not match openapi.json schemas.');
console.error('Please run: npm run sync-types to update.');
process.exit(1);
}
console.log('SUCCESS: Frontend API types are in sync with openapi.json.');
process.exit(0);
}
if (isWrite) {
fs.writeFileSync(TARGET_PATH, generated, 'utf8');
console.log('SUCCESS: Generated frontend API types successfully written to lib/api/types.ts.');
process.exit(0);
}
}
module.exports = { getTsType, generateTypes };
if (require.main === module) {
main();
}