monorise 1.14.1 → 2.0.0-dev.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 (34) hide show
  1. package/dist/base/index.d.ts +227 -1
  2. package/dist/base/index.js +383 -1
  3. package/dist/base/index.js.map +1 -1
  4. package/dist/cli/cli.js +295 -122
  5. package/dist/cli/cli.js.map +1 -1
  6. package/dist/cli/templates/files/api-keys.ts +12 -0
  7. package/dist/cli/templates/files/monorise.config.ts +2 -0
  8. package/dist/cli/templates/files/proxy-route.ts +12 -22
  9. package/dist/cli/templates/files/sst.config.ts +4 -1
  10. package/dist/cli/templates/files/ws-ticket-route.ts +21 -0
  11. package/dist/core/index.d.ts +63 -36
  12. package/dist/core/index.js +783 -208
  13. package/dist/core/index.js.map +1 -1
  14. package/dist/index.d.ts +24 -7
  15. package/dist/proxy/index.d.ts +275 -2
  16. package/dist/proxy/index.js +696 -37
  17. package/dist/proxy/index.js.map +1 -1
  18. package/dist/react/index.d.ts +2 -164
  19. package/dist/react/index.d.ts.map +1 -1
  20. package/dist/react/index.js +46 -188
  21. package/dist/react/index.js.map +1 -1
  22. package/dist/react/lib/api.d.ts +1 -2
  23. package/dist/react/lib/api.d.ts.map +1 -1
  24. package/dist/react/store/monorise.store.d.ts +0 -54
  25. package/dist/react/store/monorise.store.d.ts.map +1 -1
  26. package/dist/sst/components/monorise-core.d.ts.map +1 -1
  27. package/dist/sst/index.js +4 -1
  28. package/dist/sst/index.js.map +1 -1
  29. package/package.json +1 -1
  30. package/dist/cli/templates/files/proxy-request.ts +0 -50
  31. package/dist/react/actions/auth.action.d.ts +0 -24
  32. package/dist/react/actions/auth.action.d.ts.map +0 -1
  33. package/dist/react/services/auth.service.d.ts +0 -21
  34. package/dist/react/services/auth.service.d.ts.map +0 -1
@@ -1,38 +1,691 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
- var __hasOwnProp = Object.prototype.hasOwnProperty;
4
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
7
- for (var prop in b || (b = {}))
8
- if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
10
- if (__getOwnPropSymbols)
11
- for (var prop of __getOwnPropSymbols(b)) {
12
- if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- }
15
- return a;
16
- };
17
- var __async = (__this, __arguments, generator) => {
18
- return new Promise((resolve, reject) => {
19
- var fulfilled = (value) => {
20
- try {
21
- step(generator.next(value));
22
- } catch (e) {
23
- reject(e);
1
+ // proxy/operations.ts
2
+ var hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ var notFound = (message) => ({
5
+ ok: false,
6
+ status: 404,
7
+ message
8
+ });
9
+ var invalid = (message) => ({
10
+ ok: false,
11
+ status: 400,
12
+ message
13
+ });
14
+ var asEntityType = (entityConfig, byEntityType, entityType) => {
15
+ const declared = (from, to) => {
16
+ const fields = entityConfig && hasOwn(entityConfig, from) ? entityConfig[from].mutual?.mutualFields : void 0;
17
+ return Object.values(fields ?? {}).find(
18
+ (field) => field.entityType === to && field.mutual
19
+ )?.mutual?.asEntity?.name;
20
+ };
21
+ return declared(byEntityType, entityType) ?? declared(entityType, byEntityType);
22
+ };
23
+ var relationshipCreate = (entityConfig, relationship, requestedAsEntity) => {
24
+ const { byEntityType, byEntityId, entityType, entityId, payload } = relationship;
25
+ const asEntity = requestedAsEntity || asEntityType(entityConfig, byEntityType, entityType);
26
+ if (!asEntity) return [relationship];
27
+ return [
28
+ relationship,
29
+ {
30
+ kind: "entity",
31
+ action: "create",
32
+ entityType: asEntity,
33
+ ...payload === void 0 ? {} : { payload },
34
+ asEntityOf: { byEntityType, byEntityId, entityType, entityId },
35
+ ...relationship.operationIndex === void 0 ? {} : { operationIndex: relationship.operationIndex }
36
+ }
37
+ ];
38
+ };
39
+ var relationshipFieldOperations = (entityConfig, entityType, entityId, payload, write, operationIndex) => {
40
+ const config = entityConfig && hasOwn(entityConfig, entityType) ? entityConfig[entityType] : void 0;
41
+ const fields = config?.mutual?.mutualFields;
42
+ if (!payload || !fields) return [];
43
+ const operations = [];
44
+ for (const [field, value] of Object.entries(payload)) {
45
+ if (!hasOwn(fields, field)) continue;
46
+ const base = {
47
+ kind: "relationship",
48
+ byEntityType: entityType,
49
+ byEntityId: entityId,
50
+ entityType: fields[field].entityType,
51
+ ...operationIndex === void 0 ? {} : { operationIndex }
52
+ };
53
+ const ids = Array.isArray(value) ? value.filter((id) => typeof id === "string") : [];
54
+ for (const id of ids) {
55
+ operations.push(
56
+ ...relationshipCreate(entityConfig, {
57
+ ...base,
58
+ action: "create",
59
+ entityId: id
60
+ })
61
+ );
62
+ }
63
+ if (write === "update") operations.push({ ...base, action: "delete" });
64
+ }
65
+ return operations;
66
+ };
67
+ var entityWrite = (entityConfig, actions, entityType, entityId, payload, operationIndex, condition) => {
68
+ const index = operationIndex === void 0 ? {} : { operationIndex };
69
+ return [
70
+ ...actions.map(
71
+ (action) => ({
72
+ kind: "entity",
73
+ action,
74
+ entityType,
75
+ ...entityId === void 0 ? {} : { entityId },
76
+ ...payload === void 0 ? {} : { payload },
77
+ ...condition === void 0 ? {} : { condition },
78
+ ...index
79
+ })
80
+ ),
81
+ ...relationshipFieldOperations(
82
+ entityConfig,
83
+ entityType,
84
+ entityId,
85
+ payload,
86
+ // An upsert can update, so its relationship fields count as an update's.
87
+ actions.includes("update") ? "update" : "create",
88
+ operationIndex
89
+ )
90
+ ];
91
+ };
92
+ var transactionOperations = (entityConfig, body) => {
93
+ const entries = isRecord(body) ? body.operations : void 0;
94
+ if (!Array.isArray(entries)) {
95
+ return invalid('Request body must contain an "operations" array');
96
+ }
97
+ const operations = [];
98
+ for (const [operationIndex, entry] of entries.entries()) {
99
+ if (!isRecord(entry) || typeof entry.entityType !== "string") {
100
+ return invalid(`Operation ${operationIndex} has no entityType`);
101
+ }
102
+ const { entityType } = entry;
103
+ const entityId = typeof entry.entityId === "string" ? entry.entityId : void 0;
104
+ const payload = isRecord(entry.payload) ? entry.payload : void 0;
105
+ const condition = typeof entry.condition === "string" ? entry.condition : void 0;
106
+ switch (entry.operation) {
107
+ case "createEntity":
108
+ case "updateEntity":
109
+ operations.push(
110
+ ...entityWrite(
111
+ entityConfig,
112
+ [entry.operation === "createEntity" ? "create" : "update"],
113
+ entityType,
114
+ entityId,
115
+ payload,
116
+ operationIndex,
117
+ condition
118
+ )
119
+ );
120
+ break;
121
+ case "adjustEntity":
122
+ operations.push({
123
+ kind: "entity",
124
+ action: "adjust",
125
+ entityType,
126
+ ...entityId === void 0 ? {} : { entityId },
127
+ ...isRecord(entry.adjustments) ? { adjustments: entry.adjustments } : {},
128
+ ...condition === void 0 ? {} : { condition },
129
+ operationIndex
130
+ });
131
+ break;
132
+ case "deleteEntity":
133
+ operations.push({
134
+ kind: "entity",
135
+ action: "delete",
136
+ entityType,
137
+ ...entityId === void 0 ? {} : { entityId },
138
+ operationIndex
139
+ });
140
+ break;
141
+ case "createMutual":
142
+ case "updateMutual":
143
+ case "deleteMutual": {
144
+ if (typeof entry.byEntityType !== "string" || typeof entry.byEntityId !== "string") {
145
+ return invalid(
146
+ `Operation ${operationIndex} needs byEntityType and byEntityId`
147
+ );
148
+ }
149
+ const relationship = {
150
+ kind: "relationship",
151
+ action: entry.operation === "createMutual" ? "create" : entry.operation === "updateMutual" ? "update" : "delete",
152
+ byEntityType: entry.byEntityType,
153
+ byEntityId: entry.byEntityId,
154
+ entityType,
155
+ ...entityId === void 0 ? {} : { entityId },
156
+ ...payload === void 0 ? {} : { payload },
157
+ operationIndex
158
+ };
159
+ operations.push(
160
+ ...relationship.action === "create" ? relationshipCreate(entityConfig, relationship) : [relationship]
161
+ );
162
+ break;
163
+ }
164
+ default:
165
+ return invalid(
166
+ `Operation ${operationIndex} has an unknown operation '${String(entry.operation)}'`
167
+ );
168
+ }
169
+ }
170
+ return { ok: true, operations };
171
+ };
172
+ var decode = (segment) => {
173
+ try {
174
+ return decodeURIComponent(segment);
175
+ } catch {
176
+ return void 0;
177
+ }
178
+ };
179
+ var parseOperations = ({
180
+ method,
181
+ path,
182
+ searchParams,
183
+ body,
184
+ entityConfig
185
+ }) => {
186
+ const decoded = (path === "/" ? [] : path.split("/").slice(1)).map(decode);
187
+ if (decoded.some((segment) => !segment || segment.includes("/"))) {
188
+ return invalid("Malformed path");
189
+ }
190
+ const [root, ...rest] = decoded;
191
+ const verb = method.toUpperCase();
192
+ const payload = isRecord(body) ? body : void 0;
193
+ const unknown = notFound(`Monorise Core has no route ${verb} ${path}`);
194
+ const one = (operation) => ({
195
+ ok: true,
196
+ operations: [operation]
197
+ });
198
+ const params = (...names) => Object.fromEntries(
199
+ names.flatMap((name) => {
200
+ const value = searchParams.get(name);
201
+ return value ? [[name, value]] : [];
202
+ })
203
+ );
204
+ if (root === "entity") {
205
+ const [entityType, second, third, fourth] = rest;
206
+ if (rest.length === 1 && verb === "GET") {
207
+ return one({
208
+ kind: "entity",
209
+ action: "list",
210
+ entityType,
211
+ ...params("query", "start", "end")
212
+ });
213
+ }
214
+ if (rest.length === 1 && verb === "POST") {
215
+ const entityId = typeof payload?.entityId === "string" ? payload.entityId : void 0;
216
+ return {
217
+ ok: true,
218
+ operations: entityWrite(
219
+ entityConfig,
220
+ ["create"],
221
+ entityType,
222
+ entityId,
223
+ payload
224
+ )
225
+ };
226
+ }
227
+ if (rest.length === 4 && second === "unique" && verb === "GET") {
228
+ return one({
229
+ kind: "entity",
230
+ action: "get",
231
+ entityType,
232
+ unique: { field: third, value: fourth }
233
+ });
234
+ }
235
+ if (rest.length === 3 && third === "adjust" && verb === "POST") {
236
+ const { $condition: condition, ...adjustments } = payload ?? {};
237
+ return one({
238
+ kind: "entity",
239
+ action: "adjust",
240
+ entityType,
241
+ entityId: second,
242
+ ...payload === void 0 ? {} : { adjustments },
243
+ ...typeof condition === "string" ? { condition } : {}
244
+ });
245
+ }
246
+ if (rest.length === 2) {
247
+ const write = (actions, data = payload, condition) => ({
248
+ ok: true,
249
+ operations: entityWrite(
250
+ entityConfig,
251
+ actions,
252
+ entityType,
253
+ second,
254
+ data,
255
+ void 0,
256
+ condition
257
+ )
258
+ });
259
+ if (verb === "GET") {
260
+ return one({
261
+ kind: "entity",
262
+ action: "get",
263
+ entityType,
264
+ entityId: second
265
+ });
266
+ }
267
+ if (verb === "PUT") return write(["create", "update"]);
268
+ if (verb === "PATCH") {
269
+ if (payload === void 0) return write(["update"]);
270
+ const { $condition: condition, $where: _, ...data } = payload;
271
+ return write(
272
+ ["update"],
273
+ data,
274
+ typeof condition === "string" ? condition : void 0
275
+ );
276
+ }
277
+ if (verb === "DELETE") {
278
+ return one({
279
+ kind: "entity",
280
+ action: "delete",
281
+ entityType,
282
+ entityId: second
283
+ });
284
+ }
285
+ }
286
+ return unknown;
287
+ }
288
+ if (root === "mutual") {
289
+ const [byEntityType, byEntityId, entityType, entityId] = rest;
290
+ if (rest.length === 3 && verb === "GET") {
291
+ const chain = searchParams.get("chainEntityQuery");
292
+ const types = [
293
+ byEntityType,
294
+ ...chain ? chain.split(",") : [],
295
+ entityType
296
+ ];
297
+ return {
298
+ ok: true,
299
+ operations: types.slice(1).map(
300
+ (to, hop) => ({
301
+ kind: "relationship",
302
+ action: "read",
303
+ byEntityType: types[hop],
304
+ ...hop === 0 ? { byEntityId } : {},
305
+ entityType: to
306
+ })
307
+ )
308
+ };
309
+ }
310
+ if (rest.length === 4) {
311
+ const action = verb === "GET" ? "read" : verb === "POST" ? "create" : verb === "PATCH" ? "update" : verb === "DELETE" ? "delete" : void 0;
312
+ if (action) {
313
+ const relationship = {
314
+ kind: "relationship",
315
+ action,
316
+ byEntityType,
317
+ byEntityId,
318
+ entityType,
319
+ entityId,
320
+ ...payload === void 0 || action === "read" || action === "delete" ? {} : { payload }
321
+ };
322
+ return {
323
+ ok: true,
324
+ operations: action === "create" ? (
325
+ // CreateMutualController passes ?asEntity= to the service.
326
+ relationshipCreate(
327
+ entityConfig,
328
+ relationship,
329
+ searchParams.get("asEntity") ?? void 0
330
+ )
331
+ ) : [relationship]
332
+ };
333
+ }
334
+ }
335
+ return unknown;
336
+ }
337
+ if (root === "tag" && rest.length === 2 && verb === "GET") {
338
+ return one({
339
+ kind: "entity",
340
+ action: "list",
341
+ entityType: rest[0],
342
+ tag: rest[1],
343
+ ...params("group", "start", "end")
344
+ });
345
+ }
346
+ if (root === "transaction" && rest.length === 0 && verb === "POST") {
347
+ return transactionOperations(entityConfig, body);
348
+ }
349
+ if (root === "app") {
350
+ return one({
351
+ kind: "route",
352
+ method: verb,
353
+ path: `/${decoded.join("/")}`,
354
+ ...body === void 0 ? {} : { body }
355
+ });
356
+ }
357
+ return unknown;
358
+ };
359
+
360
+ // proxy/rules.ts
361
+ var allow = () => true;
362
+ var deny = () => false;
363
+ var hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
364
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
365
+ var own = (object, key) => isRecord2(object) && hasOwn2(object, key) ? object[key] : void 0;
366
+ var asRule = (value) => typeof value === "function" ? value : void 0;
367
+ var ruleFor = (value, action) => asRule(value) ?? asRule(own(value, action));
368
+ var outranks = (rank, than) => {
369
+ const index = rank.findIndex((value, at) => value !== than[at]);
370
+ return index !== -1 && rank[index] > than[index];
371
+ };
372
+ var matchRoute = (routes, operation) => {
373
+ if (!routes) return void 0;
374
+ const exact = asRule(own(routes, `${operation.method} ${operation.path}`));
375
+ if (exact) return { rule: exact, params: {} };
376
+ const segments = operation.path.split("/").filter(Boolean);
377
+ let best;
378
+ for (const [key, rule] of Object.entries(routes)) {
379
+ const [method, pattern] = key.split(" ");
380
+ if (method !== operation.method || !pattern || typeof rule !== "function") {
381
+ continue;
382
+ }
383
+ const parts = pattern.split("/").filter(Boolean);
384
+ const params = {};
385
+ const rest = parts.at(-1) === "*";
386
+ const fixed = rest ? parts.slice(0, -1) : parts;
387
+ if (rest ? segments.length < fixed.length : segments.length !== fixed.length) {
388
+ continue;
389
+ }
390
+ const matches = fixed.every((part, index) => {
391
+ if (part.startsWith(":")) {
392
+ params[part.slice(1)] = segments[index];
393
+ return true;
394
+ }
395
+ return part === segments[index];
396
+ });
397
+ if (!matches) continue;
398
+ const paramCount = fixed.filter((part) => part.startsWith(":")).length;
399
+ const rank = [fixed.length - paramCount, rest ? 0 : 1, -paramCount];
400
+ if (!best || outranks(rank, best.rank)) {
401
+ best = { match: { rule, params }, rank };
402
+ }
403
+ }
404
+ return best?.match;
405
+ };
406
+ var findRule = (rules, routes, operation) => {
407
+ const tableFallback = own(rules, "*");
408
+ const found = (rule, matched = operation) => rule ? { rule, operation: matched } : void 0;
409
+ if (operation.kind === "entity") {
410
+ const entity = own(rules, operation.entityType);
411
+ return found(
412
+ asRule(entity) ?? asRule(own(entity, operation.action)) ?? asRule(own(entity, "*")) ?? ruleFor(tableFallback, operation.action)
413
+ );
414
+ }
415
+ if (operation.kind === "relationship") {
416
+ const entity = own(rules, operation.byEntityType);
417
+ const mutuals = own(entity, "mutuals");
418
+ return found(
419
+ asRule(entity) ?? ruleFor(own(mutuals, operation.entityType), operation.action) ?? asRule(own(own(mutuals, operation.entityType), "*")) ?? ruleFor(own(mutuals, "*"), operation.action) ?? ruleFor(tableFallback, operation.action)
420
+ );
421
+ }
422
+ const route = matchRoute(routes, operation);
423
+ if (route) return found(route.rule, { ...operation, params: route.params });
424
+ return found(asRule(own(routes, "*")) ?? asRule(tableFallback));
425
+ };
426
+ var describeOperation = (operation) => operation.kind === "entity" ? `${operation.action} on '${operation.entityType}'` : operation.kind === "relationship" ? `${operation.action} on ${operation.byEntityType}\u2192${operation.entityType}` : `${operation.method} ${operation.path}`;
427
+ var missingRuleHint = (operation) => operation.kind === "entity" ? `rules: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => \u2026 } }` : operation.kind === "relationship" ? `rules: { '${operation.byEntityType}': { mutuals: { '${operation.entityType}': { ${operation.action}: (operation, { session }) => \u2026 } } } }` : `routes: { '${operation.method} ${operation.path}': (operation, { session }) => \u2026 }`;
428
+ var forbidden = (message, operation) => new Response(
429
+ JSON.stringify({
430
+ code: "FORBIDDEN",
431
+ message,
432
+ ..."operationIndex" in operation && operation.operationIndex !== void 0 ? { operationIndex: operation.operationIndex } : {}
433
+ }),
434
+ { status: 403, headers: { "content-type": "application/json" } }
435
+ );
436
+ var proxyError = (message, operation) => new Response(
437
+ JSON.stringify({
438
+ code: "PROXY_ERROR",
439
+ message,
440
+ ...operation && "operationIndex" in operation && operation.operationIndex !== void 0 ? { operationIndex: operation.operationIndex } : {}
441
+ }),
442
+ { status: 500, headers: { "content-type": "application/json" } }
443
+ );
444
+ var checkOperations = async ({
445
+ operations,
446
+ rules,
447
+ routes,
448
+ context,
449
+ logMissingRules = false
450
+ }) => {
451
+ for (const operation of operations) {
452
+ const found = findRule(rules, routes, operation);
453
+ if (!found) {
454
+ if (logMissingRules) {
455
+ console.warn(
456
+ `[monorise/proxy] No rule for ${describeOperation(operation)}. Add one: ${missingRuleHint(operation)}`
457
+ );
24
458
  }
459
+ return forbidden(
460
+ `No proxy rule for ${describeOperation(operation)}`,
461
+ operation
462
+ );
463
+ }
464
+ let result;
465
+ try {
466
+ result = await found.rule(found.operation, context);
467
+ } catch (error) {
468
+ const what = `The rule for ${describeOperation(operation)}`;
469
+ console.error(`[monorise/proxy] ${what} threw`, error);
470
+ return proxyError(`${what} threw`, operation);
471
+ }
472
+ if (result instanceof Response) return result;
473
+ if (result !== true) {
474
+ return forbidden(
475
+ `Proxy rule refused ${describeOperation(operation)}`,
476
+ operation
477
+ );
478
+ }
479
+ }
480
+ return void 0;
481
+ };
482
+
483
+ // proxy/handler.ts
484
+ var FORWARDED_HEADERS = [
485
+ "content-type",
486
+ "accept",
487
+ "accept-language",
488
+ "x-request-id"
489
+ ];
490
+ var DROPPED_RESPONSE_HEADERS = [
491
+ "content-encoding",
492
+ "content-length",
493
+ "transfer-encoding",
494
+ "connection"
495
+ ];
496
+ var hasOwn3 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
497
+ var env = (name) => typeof process === "undefined" ? void 0 : process.env?.[name];
498
+ var json = (status, body) => new Response(JSON.stringify(body), {
499
+ status,
500
+ headers: { "content-type": "application/json" }
501
+ });
502
+ var NO_STORE = "private, no-store";
503
+ var withNoStore = (response) => {
504
+ if (response.headers.has("cache-control")) return response;
505
+ const headers = new Headers(response.headers);
506
+ headers.set("cache-control", NO_STORE);
507
+ return new Response(response.body, {
508
+ status: response.status,
509
+ statusText: response.statusText,
510
+ headers
511
+ });
512
+ };
513
+ var callbackThrew = (what, error) => {
514
+ console.error(`[monorise/proxy] ${what} threw`, error);
515
+ return proxyError(`${what} threw`);
516
+ };
517
+ var unauthorized = () => json(401, { code: "UNAUTHORIZED", message: "Unauthorized" });
518
+ var misconfigured = (message) => {
519
+ console.error(`[monorise/proxy] ${message}`);
520
+ return json(500, { code: "PROXY_MISCONFIGURED", message });
521
+ };
522
+ var createProxyHandler = (options) => {
523
+ const multiple = options.callers !== void 0 || options.caller !== void 0;
524
+ if (multiple && (typeof options.caller !== "function" || typeof options.callers !== "object" || options.apiKey !== void 0 || options.rules !== void 0 || options.routes !== void 0)) {
525
+ throw new Error(
526
+ "createProxyHandler takes either caller and callers, or apiKey and rules"
527
+ );
528
+ }
529
+ const basePath = `/${(options.basePath ?? "/api/core").replace(/^\/+|\/+$/g, "")}`;
530
+ const entityConfig = options.config?.EntityConfig;
531
+ const logMissingRules = options.logMissingRules ?? env("NODE_ENV") !== "production";
532
+ const coreClient = (apiBaseUrl, apiKey) => {
533
+ const coreFetch = (path, init = {}) => {
534
+ const headers = new Headers(init.headers);
535
+ headers.set("x-api-key", apiKey);
536
+ return fetch(`${apiBaseUrl}/core${path}`, {
537
+ cache: "no-store",
538
+ ...init,
539
+ headers
540
+ });
25
541
  };
26
- var rejected = (value) => {
542
+ return { get: (path) => coreFetch(path), fetch: coreFetch };
543
+ };
544
+ const prepare = async (request) => {
545
+ const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.clone().arrayBuffer();
546
+ let authenticated;
547
+ try {
548
+ authenticated = options.authenticate ? await options.authenticate(request) : void 0;
549
+ } catch (error) {
550
+ return callbackThrew("authenticate", error);
551
+ }
552
+ if (authenticated instanceof Response) return authenticated;
553
+ const session = authenticated ?? void 0;
554
+ let caller;
555
+ let entry;
556
+ if (multiple) {
27
557
  try {
28
- step(generator.throw(value));
29
- } catch (e) {
30
- reject(e);
558
+ caller = await options.caller?.({ session, request });
559
+ } catch (error) {
560
+ return callbackThrew("caller", error);
31
561
  }
562
+ const callers = options.callers ?? {};
563
+ entry = caller !== void 0 && hasOwn3(callers, caller) ? callers[caller] : void 0;
564
+ } else if (!options.authenticate || session !== void 0) {
565
+ entry = options;
566
+ }
567
+ if (!entry) return unauthorized();
568
+ if (!entry.apiKey) {
569
+ return misconfigured(
570
+ caller === void 0 ? "No apiKey is set" : `No apiKey is set for caller '${caller}'`
571
+ );
572
+ }
573
+ const apiBaseUrl = (options.apiBaseUrl ?? env("API_BASE_URL"))?.replace(
574
+ /\/+$/,
575
+ ""
576
+ );
577
+ if (!apiBaseUrl) {
578
+ return misconfigured("No apiBaseUrl is set, and API_BASE_URL is empty");
579
+ }
580
+ const url = new URL(request.url);
581
+ if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) {
582
+ return json(404, {
583
+ code: "NOT_FOUND",
584
+ message: `The proxy serves paths under ${basePath}`
585
+ });
586
+ }
587
+ const path = url.pathname.slice(basePath.length) || "/";
588
+ const text = body ? new TextDecoder().decode(body) : "";
589
+ let parsed;
590
+ if (text.trim()) {
591
+ try {
592
+ parsed = JSON.parse(text);
593
+ } catch {
594
+ if (!path.startsWith("/app/")) {
595
+ return json(400, {
596
+ code: "BAD_REQUEST",
597
+ message: "Request body must be JSON"
598
+ });
599
+ }
600
+ }
601
+ }
602
+ const result = parseOperations({
603
+ method: request.method,
604
+ path,
605
+ searchParams: url.searchParams,
606
+ body: parsed,
607
+ entityConfig
608
+ });
609
+ if (!result.ok) {
610
+ return json(result.status, {
611
+ code: result.status === 404 ? "NOT_FOUND" : "BAD_REQUEST",
612
+ message: result.message
613
+ });
614
+ }
615
+ const context = {
616
+ session,
617
+ request,
618
+ core: coreClient(apiBaseUrl, entry.apiKey)
32
619
  };
33
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
34
- step((generator = generator.apply(__this, __arguments)).next());
35
- });
620
+ const refusal = await checkOperations({
621
+ operations: result.operations,
622
+ rules: entry.rules,
623
+ routes: entry.routes,
624
+ context,
625
+ logMissingRules
626
+ });
627
+ if (refusal) return refusal;
628
+ return {
629
+ caller,
630
+ session,
631
+ apiKey: entry.apiKey,
632
+ apiBaseUrl,
633
+ target: `${path}${url.search}`,
634
+ body: body && body.byteLength > 0 ? body : void 0,
635
+ operations: result.operations
636
+ };
637
+ };
638
+ const checkRequest = async (request) => {
639
+ const prepared = await prepare(request);
640
+ if (prepared instanceof Response) {
641
+ return { allowed: false, response: withNoStore(prepared) };
642
+ }
643
+ const { caller, session, operations } = prepared;
644
+ return { allowed: true, caller, session, operations };
645
+ };
646
+ const handle = async (request) => withNoStore(await forward(request));
647
+ const forward = async (request) => {
648
+ const prepared = await prepare(request);
649
+ if (prepared instanceof Response) return prepared;
650
+ const headers = new Headers();
651
+ for (const name of FORWARDED_HEADERS) {
652
+ const value = request.headers.get(name);
653
+ if (value !== null) headers.set(name, value);
654
+ }
655
+ headers.set("x-api-key", prepared.apiKey);
656
+ let response;
657
+ try {
658
+ response = await fetch(`${prepared.apiBaseUrl}/core${prepared.target}`, {
659
+ method: request.method,
660
+ headers,
661
+ body: prepared.body,
662
+ cache: "no-store"
663
+ });
664
+ } catch (error) {
665
+ console.error("[monorise/proxy] Monorise Core is unreachable", error);
666
+ return json(502, {
667
+ code: "BAD_GATEWAY",
668
+ message: "Monorise Core is unreachable"
669
+ });
670
+ }
671
+ const responseHeaders = new Headers(response.headers);
672
+ for (const name of DROPPED_RESPONSE_HEADERS) responseHeaders.delete(name);
673
+ return new Response(response.body, {
674
+ status: response.status,
675
+ statusText: response.statusText,
676
+ headers: responseHeaders
677
+ });
678
+ };
679
+ const alias = (request) => handle(request);
680
+ return {
681
+ handle,
682
+ checkRequest,
683
+ GET: alias,
684
+ POST: alias,
685
+ PUT: alias,
686
+ PATCH: alias,
687
+ DELETE: alias
688
+ };
36
689
  };
37
690
 
38
691
  // index.ts
@@ -48,21 +701,24 @@ var getApiBaseUrl = () => {
48
701
  var getApiKey = () => {
49
702
  return process.env.MONORISE_API_KEY || process.env.API_KEY || "";
50
703
  };
51
- var generateWebSocketTicket = (options) => __async(null, null, function* () {
704
+ var generateWebSocketTicket = async (options) => {
52
705
  const apiBaseUrl = getApiBaseUrl();
53
706
  const apiKey = getApiKey();
54
707
  const { entityType, entityId, feedTypes } = options;
55
- const response = yield fetch(
708
+ const response = await fetch(
56
709
  // `/core` is monorise's own Hono basePath (packages/core/handles/app.ts),
57
710
  // not part of API_BASE_URL -- the React default endpoint spells the same
58
711
  // path as `/api/core/ws/ticket/...`.
59
712
  `${apiBaseUrl}/core/ws/ticket/${entityType}/${entityId}`,
60
713
  {
61
714
  method: "POST",
62
- headers: __spreadValues({
63
- "Content-Type": "application/json"
64
- }, apiKey && { "x-api-key": apiKey }),
65
- body: JSON.stringify(__spreadValues({}, feedTypes && { feedTypes }))
715
+ headers: {
716
+ "Content-Type": "application/json",
717
+ ...apiKey && { "x-api-key": apiKey }
718
+ },
719
+ body: JSON.stringify({
720
+ ...feedTypes && { feedTypes }
721
+ })
66
722
  }
67
723
  );
68
724
  if (!response.ok) {
@@ -71,8 +727,11 @@ var generateWebSocketTicket = (options) => __async(null, null, function* () {
71
727
  );
72
728
  }
73
729
  return response.json();
74
- });
730
+ };
75
731
  export {
732
+ allow,
733
+ createProxyHandler,
734
+ deny,
76
735
  generateWebSocketTicket
77
736
  };
78
737
  //# sourceMappingURL=index.js.map