@driveflux/api-functions 0.0.6 → 0.0.7-next.1

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.
Files changed (53) hide show
  1. package/dist/auth/confirm.js +73 -327
  2. package/dist/auth/emails.js +43 -210
  3. package/dist/auth/formatter.js +11 -11
  4. package/dist/auth/otp.js +122 -392
  5. package/dist/auth/register.js +100 -396
  6. package/dist/auth/tokens.d.ts +3 -3
  7. package/dist/auth/tokens.js +115 -430
  8. package/dist/auth/verifications.d.ts.map +1 -1
  9. package/dist/auth/verifications.js +191 -514
  10. package/dist/auth/verifications.js.map +1 -1
  11. package/dist/constants.js +5 -4
  12. package/dist/mailjet/calls/manage-contacts-in-list.js +22 -166
  13. package/dist/mailjet/calls/manage-subscription-status.js +13 -153
  14. package/dist/mailjet/calls/request-service.d.ts +1 -1
  15. package/dist/mailjet/calls/request-service.d.ts.map +1 -1
  16. package/dist/mailjet/calls/request-service.js +18 -183
  17. package/dist/mailjet/refresh-email-preferences.js +26 -225
  18. package/dist/mailjet/set-contact.js +23 -214
  19. package/dist/mailjet/types.js +2 -1
  20. package/dist/mailjet/utils/convert-to-array.js +9 -58
  21. package/dist/mailjet/utils/extract-email-preferences.js +41 -217
  22. package/dist/mailjet/utils/lists.js +30 -249
  23. package/dist/mailjet/utils/update-email-references.js +27 -208
  24. package/dist/notion/client.js +48 -197
  25. package/dist/notion/helpful.js +29 -170
  26. package/dist/notion/schemas/block.js +49 -43
  27. package/dist/notion/schemas/common.js +17 -14
  28. package/dist/notion/schemas/database.js +125 -159
  29. package/dist/notion/schemas/emoji.js +3 -2
  30. package/dist/notion/schemas/file.js +10 -10
  31. package/dist/notion/schemas/kb.js +9 -8
  32. package/dist/notion/schemas/page.js +126 -171
  33. package/dist/notion/schemas/parent.js +9 -8
  34. package/dist/notion/schemas/user.js +21 -20
  35. package/dist/reservation/agree.js +19 -158
  36. package/dist/reservation/checks.js +23 -178
  37. package/dist/reservation/display-vehicle.d.ts +37 -37
  38. package/dist/reservation/display-vehicle.d.ts.map +1 -1
  39. package/dist/reservation/display-vehicle.js +142 -514
  40. package/dist/reservation/fetch-or-create.js +197 -482
  41. package/dist/reservation/invoice.js +198 -496
  42. package/dist/reservation/payer.js +28 -177
  43. package/dist/reservation/reserve.js +31 -191
  44. package/dist/reservation/types.js +2 -1
  45. package/dist/reservation/vehicle.js +24 -186
  46. package/dist/slack.d.ts +2 -2
  47. package/dist/slack.d.ts.map +1 -1
  48. package/dist/slack.js +67 -273
  49. package/dist/validation.js +81 -139
  50. package/dist/vehicle/vehicle-pricing/constants.js +33 -36
  51. package/dist/vehicle/vehicle-pricing/index.js +99 -257
  52. package/dist/vehicle/vehicle-pricing/types.js +2 -1
  53. package/package.json +12 -12
@@ -1,202 +1,3 @@
1
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
- try {
3
- var info = gen[key](arg);
4
- var value = info.value;
5
- } catch (error) {
6
- reject(error);
7
- return;
8
- }
9
- if (info.done) {
10
- resolve(value);
11
- } else {
12
- Promise.resolve(value).then(_next, _throw);
13
- }
14
- }
15
- function _async_to_generator(fn) {
16
- return function() {
17
- var self = this, args = arguments;
18
- return new Promise(function(resolve, reject) {
19
- var gen = fn.apply(self, args);
20
- function _next(value) {
21
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
- }
23
- function _throw(err) {
24
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
- }
26
- _next(undefined);
27
- });
28
- };
29
- }
30
- function _define_property(obj, key, value) {
31
- if (key in obj) {
32
- Object.defineProperty(obj, key, {
33
- value: value,
34
- enumerable: true,
35
- configurable: true,
36
- writable: true
37
- });
38
- } else {
39
- obj[key] = value;
40
- }
41
- return obj;
42
- }
43
- function _object_spread(target) {
44
- for(var i = 1; i < arguments.length; i++){
45
- var source = arguments[i] != null ? arguments[i] : {};
46
- var ownKeys = Object.keys(source);
47
- if (typeof Object.getOwnPropertySymbols === "function") {
48
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
49
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
50
- }));
51
- }
52
- ownKeys.forEach(function(key) {
53
- _define_property(target, key, source[key]);
54
- });
55
- }
56
- return target;
57
- }
58
- function ownKeys(object, enumerableOnly) {
59
- var keys = Object.keys(object);
60
- if (Object.getOwnPropertySymbols) {
61
- var symbols = Object.getOwnPropertySymbols(object);
62
- if (enumerableOnly) {
63
- symbols = symbols.filter(function(sym) {
64
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
65
- });
66
- }
67
- keys.push.apply(keys, symbols);
68
- }
69
- return keys;
70
- }
71
- function _object_spread_props(target, source) {
72
- source = source != null ? source : {};
73
- if (Object.getOwnPropertyDescriptors) {
74
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
75
- } else {
76
- ownKeys(Object(source)).forEach(function(key) {
77
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
78
- });
79
- }
80
- return target;
81
- }
82
- function _object_without_properties(source, excluded) {
83
- if (source == null) return {};
84
- var target = _object_without_properties_loose(source, excluded);
85
- var key, i;
86
- if (Object.getOwnPropertySymbols) {
87
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
88
- for(i = 0; i < sourceSymbolKeys.length; i++){
89
- key = sourceSymbolKeys[i];
90
- if (excluded.indexOf(key) >= 0) continue;
91
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
92
- target[key] = source[key];
93
- }
94
- }
95
- return target;
96
- }
97
- function _object_without_properties_loose(source, excluded) {
98
- if (source == null) return {};
99
- var target = {};
100
- var sourceKeys = Object.keys(source);
101
- var key, i;
102
- for(i = 0; i < sourceKeys.length; i++){
103
- key = sourceKeys[i];
104
- if (excluded.indexOf(key) >= 0) continue;
105
- target[key] = source[key];
106
- }
107
- return target;
108
- }
109
- function _ts_generator(thisArg, body) {
110
- var f, y, t, _ = {
111
- label: 0,
112
- sent: function() {
113
- if (t[0] & 1) throw t[1];
114
- return t[1];
115
- },
116
- trys: [],
117
- ops: []
118
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
119
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
120
- return this;
121
- }), g;
122
- function verb(n) {
123
- return function(v) {
124
- return step([
125
- n,
126
- v
127
- ]);
128
- };
129
- }
130
- function step(op) {
131
- if (f) throw new TypeError("Generator is already executing.");
132
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
133
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
134
- if (y = 0, t) op = [
135
- op[0] & 2,
136
- t.value
137
- ];
138
- switch(op[0]){
139
- case 0:
140
- case 1:
141
- t = op;
142
- break;
143
- case 4:
144
- _.label++;
145
- return {
146
- value: op[1],
147
- done: false
148
- };
149
- case 5:
150
- _.label++;
151
- y = op[1];
152
- op = [
153
- 0
154
- ];
155
- continue;
156
- case 7:
157
- op = _.ops.pop();
158
- _.trys.pop();
159
- continue;
160
- default:
161
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
162
- _ = 0;
163
- continue;
164
- }
165
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
166
- _.label = op[1];
167
- break;
168
- }
169
- if (op[0] === 6 && _.label < t[1]) {
170
- _.label = t[1];
171
- t = op;
172
- break;
173
- }
174
- if (t && _.label < t[2]) {
175
- _.label = t[2];
176
- _.ops.push(op);
177
- break;
178
- }
179
- if (t[2]) _.ops.pop();
180
- _.trys.pop();
181
- continue;
182
- }
183
- op = body.call(thisArg, _);
184
- } catch (e) {
185
- op = [
186
- 6,
187
- e
188
- ];
189
- y = 0;
190
- } finally{
191
- f = t = 0;
192
- }
193
- if (op[0] & 5) throw op[1];
194
- return {
195
- value: op[0] ? op[1] : void 0,
196
- done: true
197
- };
198
- }
199
- }
200
1
  import { cleanupPhoneNumber } from '@driveflux/api-functions/auth/formatter';
201
2
  import { refreshEmailPreferences } from '@driveflux/api-functions/mailjet/refresh-email-preferences';
202
3
  import { dateValidation } from '@driveflux/api-functions/validation';
@@ -214,211 +15,114 @@ import { SALT_ROUNDS } from '../constants.js';
214
15
  import { setContactInList } from '../mailjet/set-contact';
215
16
  import { clearToken, verifyToken } from './tokens';
216
17
  import { sendVerificationEmail } from './verifications.js';
217
- var Body = z.object({
18
+ const Body = z.object({
218
19
  firstName: z.string(),
219
20
  lastName: z.string(),
220
- phoneNumber: z.string().transform(function(s) {
221
- return s.replace(/[\s-]/g, '');
222
- }),
223
- authMethod: z.enum([
224
- 'mobile',
225
- 'email',
226
- 'facebook',
227
- 'google',
228
- 'apple'
229
- ]),
21
+ phoneNumber: z.string().transform((s) => s.replace(/[\s-]/g, '')),
22
+ authMethod: z.enum(['mobile', 'email', 'facebook', 'google', 'apple']),
230
23
  code: z.string().optional().nullable(),
231
24
  keepCode: z.boolean().optional().default(false),
232
- email: z.string().email().transform(function(s) {
233
- return s.toLowerCase().trim();
234
- }),
235
- dateOfBirth: dateValidation.refine(function(d) {
25
+ email: z
26
+ .string()
27
+ .email()
28
+ .transform((s) => s.toLowerCase().trim()),
29
+ dateOfBirth: dateValidation
30
+ .refine((d) => {
236
31
  return isAfter(d, subYears(new Date(), 25));
237
32
  }, {
238
- path: [
239
- 'dateOfBirth'
240
- ],
241
- message: 'You must be at least 25 years old to signup for the service.'
242
- }).optional(),
33
+ path: ['dateOfBirth'],
34
+ message: 'You must be at least 25 years old to signup for the service.',
35
+ })
36
+ .optional(),
243
37
  password: z.string().min(6).optional(),
244
38
  noMarketing: z.boolean().optional(),
245
39
  pageSource: z.string().optional().nullable(),
246
- skipPassword: z.boolean().optional().nullable()
40
+ skipPassword: z.boolean().optional().nullable(),
247
41
  });
248
- export var handleRegister = function(b, xForwardedFor) {
249
- return _async_to_generator(function() {
250
- var _Body_parse, noMarketing, password, authMethod, phoneNumber, code, keepCode, pageSource, skipPassword, body, phoneNumberVerified, tokenResult, foundUser, formattedPohoneNumber, id, hashedPassword, user, token;
251
- return _ts_generator(this, function(_state) {
252
- switch(_state.label){
253
- case 0:
254
- _Body_parse = Body.parse(b), noMarketing = _Body_parse.noMarketing, password = _Body_parse.password, authMethod = _Body_parse.authMethod, phoneNumber = _Body_parse.phoneNumber, code = _Body_parse.code, keepCode = _Body_parse.keepCode, pageSource = _Body_parse.pageSource, skipPassword = _Body_parse.skipPassword, body = _object_without_properties(_Body_parse, [
255
- "noMarketing",
256
- "password",
257
- "authMethod",
258
- "phoneNumber",
259
- "code",
260
- "keepCode",
261
- "pageSource",
262
- "skipPassword"
263
- ]);
264
- phoneNumberVerified = false;
265
- if (!code) return [
266
- 3,
267
- 4
268
- ];
269
- return [
270
- 4,
271
- verifyToken(code, {
272
- scope: 'verify-phone'
273
- })
274
- ];
275
- case 1:
276
- tokenResult = _state.sent();
277
- if (tokenResult.err) {
278
- return [
279
- 2,
280
- new Err(makeProblem(PROBLEM_CONFLICT, 'Invalid OTP token'))
281
- ];
282
- }
283
- if (!!keepCode) return [
284
- 3,
285
- 3
286
- ];
287
- return [
288
- 4,
289
- clearToken(tokenResult.val.id)
290
- ];
291
- case 2:
292
- _state.sent();
293
- _state.label = 3;
294
- case 3:
295
- phoneNumberVerified = true;
296
- _state.label = 4;
297
- case 4:
298
- if (!password && !skipPassword) {
299
- return [
300
- 2,
301
- new Err(makeProblem(PROBLEM_CONFLICT, 'Password is invalid'))
302
- ];
303
- }
304
- return [
305
- 4,
306
- prisma.user.findFirst({
307
- where: {
308
- email: body.email
309
- }
310
- })
311
- ];
312
- case 5:
313
- foundUser = _state.sent();
314
- if (foundUser) {
315
- return [
316
- 2,
317
- new Err(makeProblem(PROBLEM_CONFLICT, 'A user with this email address already exists. Did you mean to login?'))
318
- ];
319
- }
320
- formattedPohoneNumber = cleanupPhoneNumber(phoneNumber);
321
- id = generateId('User');
322
- return [
323
- 4,
324
- bcrypt.hash(password !== null && password !== void 0 ? password : nanoid(), SALT_ROUNDS)
325
- ];
326
- case 6:
327
- hashedPassword = _state.sent();
328
- return [
329
- 4,
330
- prisma.user.create({
331
- data: _object_spread_props(_object_spread({
332
- id: id,
333
- password: hashedPassword
334
- }, body), {
335
- phoneNumber: formattedPohoneNumber,
336
- preferredCurrency: 'MYR',
337
- preferredLocale: 'en',
338
- phoneNumberVerified: phoneNumberVerified,
339
- consented: true,
340
- groups: [
341
- 'member'
342
- ],
343
- consents: {
344
- create: {
345
- id: generateId('UserConsent'),
346
- ipAddress: Array.isArray(xForwardedFor) ? (xForwardedFor === null || xForwardedFor === void 0 ? void 0 : xForwardedFor[0]) || '0.0.0.0' : xForwardedFor || '0.0.0.0',
347
- consentType: 'terms',
348
- email: body.email
349
- }
350
- },
351
- signupParams: {
352
- method: authMethod,
353
- source: pageSource
354
- },
355
- registrationComplete: true,
356
- accounts: {
357
- create: {
358
- id: generateId('Account'),
359
- object: 'account',
360
- type: 'default',
361
- provider: 'credentials',
362
- providerAccountId: id
363
- }
364
- }
365
- })
366
- })
367
- ];
368
- case 7:
369
- user = _state.sent();
370
- return [
371
- 4,
372
- prisma.token.create({
373
- data: {
374
- id: generateId('Token'),
375
- user: {
376
- connect: {
377
- id: user.id
378
- }
379
- },
380
- expiresAt: addDays(new Date(), 365),
381
- scope: 'all'
382
- }
383
- })
384
- ];
385
- case 8:
386
- token = _state.sent();
387
- // We don't want this to be a task. It should be instant
388
- return [
389
- 4,
390
- sendVerificationEmail(user.id)
391
- ];
392
- case 9:
393
- _state.sent();
394
- if (!!noMarketing) return [
395
- 3,
396
- 11
397
- ];
398
- return [
399
- 4,
400
- setContactInList(user.id, {
401
- generalMarketing: true
402
- })
403
- ];
404
- case 10:
405
- _state.sent();
406
- _state.label = 11;
407
- case 11:
408
- return [
409
- 4,
410
- refreshEmailPreferences(user.id)
411
- ];
412
- case 12:
413
- _state.sent();
414
- return [
415
- 2,
416
- new Ok({
417
- token: token,
418
- user: user
419
- })
420
- ];
421
- }
422
- });
423
- })();
42
+ export const handleRegister = async (b, xForwardedFor) => {
43
+ const { noMarketing, password, authMethod, phoneNumber, code, keepCode, pageSource, skipPassword, ...body } = Body.parse(b);
44
+ let phoneNumberVerified = false;
45
+ if (code) {
46
+ const tokenResult = await verifyToken(code, { scope: 'verify-phone' });
47
+ if (tokenResult.err) {
48
+ return new Err(makeProblem(PROBLEM_CONFLICT, 'Invalid OTP token'));
49
+ }
50
+ if (!keepCode) {
51
+ await clearToken(tokenResult.val.id);
52
+ }
53
+ phoneNumberVerified = true;
54
+ }
55
+ if (!password && !skipPassword) {
56
+ return new Err(makeProblem(PROBLEM_CONFLICT, 'Password is invalid'));
57
+ }
58
+ // Check if the user exists
59
+ const foundUser = await prisma.user.findFirst({
60
+ where: { email: body.email },
61
+ });
62
+ if (foundUser) {
63
+ return new Err(makeProblem(PROBLEM_CONFLICT, 'A user with this email address already exists. Did you mean to login?'));
64
+ }
65
+ const formattedPohoneNumber = cleanupPhoneNumber(phoneNumber);
66
+ const id = generateId('User');
67
+ const hashedPassword = await bcrypt.hash(password ?? nanoid(), SALT_ROUNDS);
68
+ const user = await prisma.user.create({
69
+ data: {
70
+ id,
71
+ password: hashedPassword,
72
+ ...body,
73
+ phoneNumber: formattedPohoneNumber,
74
+ preferredCurrency: 'MYR',
75
+ preferredLocale: 'en',
76
+ phoneNumberVerified,
77
+ consented: true,
78
+ groups: ['member'],
79
+ consents: {
80
+ create: {
81
+ id: generateId('UserConsent'),
82
+ ipAddress: Array.isArray(xForwardedFor)
83
+ ? xForwardedFor?.[0] || '0.0.0.0'
84
+ : xForwardedFor || '0.0.0.0',
85
+ consentType: 'terms',
86
+ email: body.email,
87
+ },
88
+ },
89
+ signupParams: {
90
+ method: authMethod,
91
+ source: pageSource,
92
+ },
93
+ registrationComplete: true,
94
+ accounts: {
95
+ create: {
96
+ id: generateId('Account'),
97
+ object: 'account',
98
+ type: 'default',
99
+ provider: 'credentials',
100
+ providerAccountId: id,
101
+ },
102
+ },
103
+ },
104
+ });
105
+ const token = await prisma.token.create({
106
+ data: {
107
+ id: generateId('Token'),
108
+ user: {
109
+ connect: {
110
+ id: user.id,
111
+ },
112
+ },
113
+ expiresAt: addDays(new Date(), 365),
114
+ scope: 'all',
115
+ },
116
+ });
117
+ // We don't want this to be a task. It should be instant
118
+ await sendVerificationEmail(user.id);
119
+ if (!noMarketing) {
120
+ await setContactInList(user.id, { generalMarketing: true });
121
+ }
122
+ await refreshEmailPreferences(user.id);
123
+ return new Ok({
124
+ token,
125
+ user,
126
+ });
424
127
  };
128
+ //# sourceMappingURL=register.js.map
@@ -8,7 +8,7 @@ type VerifyTokenOptions = {
8
8
  includeUser?: boolean;
9
9
  };
10
10
  export declare const createToken: (userId: string | null, type: "email" | "phoneNumber", value: string, providedExpiresAt?: Date) => Promise<{
11
- object: import("@driveflux/db/enums").TokenObject;
11
+ object: import("@driveflux/db").TokenObject;
12
12
  id: string;
13
13
  metadata: PrismaJson.AnyMetadata | null;
14
14
  createdAt: Date;
@@ -24,7 +24,7 @@ export declare const createToken: (userId: string | null, type: "email" | "phone
24
24
  lastUsed: Date | null;
25
25
  } | undefined>;
26
26
  export declare const createEmailToken: (userId: string, email: string) => Promise<{
27
- object: import("@driveflux/db/enums").TokenObject;
27
+ object: import("@driveflux/db").TokenObject;
28
28
  id: string;
29
29
  metadata: PrismaJson.AnyMetadata | null;
30
30
  createdAt: Date;
@@ -40,7 +40,7 @@ export declare const createEmailToken: (userId: string, email: string) => Promis
40
40
  lastUsed: Date | null;
41
41
  } | undefined>;
42
42
  export declare const createSMSToken: (userId: string | null, phoneNumber: string) => Promise<{
43
- object: import("@driveflux/db/enums").TokenObject;
43
+ object: import("@driveflux/db").TokenObject;
44
44
  id: string;
45
45
  metadata: PrismaJson.AnyMetadata | null;
46
46
  createdAt: Date;