@casual-simulation/aux-records 3.4.6-alpha.14601027727 → 3.5.0-alpha.15117651144

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 (211) hide show
  1. package/AIController.js +835 -890
  2. package/AIController.js.map +1 -1
  3. package/AIHumeInterface.js +43 -54
  4. package/AIHumeInterface.js.map +1 -1
  5. package/AIOpenAIRealtimeInterface.js +60 -71
  6. package/AIOpenAIRealtimeInterface.js.map +1 -1
  7. package/AnthropicAIChatInterface.js +96 -142
  8. package/AnthropicAIChatInterface.js.map +1 -1
  9. package/AuthController.d.ts +3 -2
  10. package/AuthController.js +1907 -1933
  11. package/AuthController.js.map +1 -1
  12. package/AuthStore.d.ts +1 -10
  13. package/BlockadeLabsGenerateSkyboxInterface.js +57 -72
  14. package/BlockadeLabsGenerateSkyboxInterface.js.map +1 -1
  15. package/CachingConfigStore.js +30 -45
  16. package/CachingConfigStore.js.map +1 -1
  17. package/CachingPolicyStore.d.ts +8 -2
  18. package/CachingPolicyStore.js +108 -135
  19. package/CachingPolicyStore.js.map +1 -1
  20. package/ComIdConfig.d.ts +18 -18
  21. package/ComIdConfig.js.map +1 -1
  22. package/ConsoleAuthMessenger.js +7 -20
  23. package/ConsoleAuthMessenger.js.map +1 -1
  24. package/DataRecordsController.d.ts +2 -2
  25. package/DataRecordsController.js +369 -377
  26. package/DataRecordsController.js.map +1 -1
  27. package/DataRecordsStore.d.ts +1 -1
  28. package/DataRecordsStore.js +1 -1
  29. package/DataRecordsStore.js.map +1 -1
  30. package/EventRecordsController.js +226 -240
  31. package/EventRecordsController.js.map +1 -1
  32. package/FileRecordsController.d.ts +13 -2
  33. package/FileRecordsController.js +458 -450
  34. package/FileRecordsController.js.map +1 -1
  35. package/GoogleAIChatInterface.js +133 -179
  36. package/GoogleAIChatInterface.js.map +1 -1
  37. package/LivekitController.js +43 -54
  38. package/LivekitController.js.map +1 -1
  39. package/LoomController.js +64 -75
  40. package/LoomController.js.map +1 -1
  41. package/MemoryAuthMessenger.js +10 -23
  42. package/MemoryAuthMessenger.js.map +1 -1
  43. package/MemoryCache.js +18 -35
  44. package/MemoryCache.js.map +1 -1
  45. package/MemoryFileRecordsLookup.js +105 -125
  46. package/MemoryFileRecordsLookup.js.map +1 -1
  47. package/MemoryModerationJobProvider.js +17 -30
  48. package/MemoryModerationJobProvider.js.map +1 -1
  49. package/MemoryRateLimiter.js +12 -27
  50. package/MemoryRateLimiter.js.map +1 -1
  51. package/MemoryStore.d.ts +18 -6
  52. package/MemoryStore.js +1879 -1997
  53. package/MemoryStore.js.map +1 -1
  54. package/MetricsStore.d.ts +2 -2
  55. package/ModerationController.js +186 -200
  56. package/ModerationController.js.map +1 -1
  57. package/OpenAIChatInterface.js +105 -135
  58. package/OpenAIChatInterface.js.map +1 -1
  59. package/OpenAIImageInterface.js +57 -51
  60. package/OpenAIImageInterface.js.map +1 -1
  61. package/PolicyController.d.ts +150 -10
  62. package/PolicyController.js +1546 -1299
  63. package/PolicyController.js.map +1 -1
  64. package/PolicyStore.d.ts +110 -2
  65. package/PolicyStore.js +36 -1
  66. package/PolicyStore.js.map +1 -1
  67. package/PrivoClient.js +398 -435
  68. package/PrivoClient.js.map +1 -1
  69. package/RateLimitController.js +25 -36
  70. package/RateLimitController.js.map +1 -1
  71. package/RecordsClient.js +51 -74
  72. package/RecordsClient.js.map +1 -1
  73. package/RecordsController.d.ts +2 -42
  74. package/RecordsController.js +1026 -1182
  75. package/RecordsController.js.map +1 -1
  76. package/RecordsServer.d.ts +196 -27
  77. package/RecordsServer.js +1701 -1343
  78. package/RecordsServer.js.map +1 -1
  79. package/RecordsStore.d.ts +1 -10
  80. package/RecordsStore.js.map +1 -1
  81. package/ServerConfig.d.ts +339 -195
  82. package/ServerConfig.js +13 -0
  83. package/ServerConfig.js.map +1 -1
  84. package/SloydInterface.js +62 -75
  85. package/SloydInterface.js.map +1 -1
  86. package/StabilityAIImageInterface.js +150 -167
  87. package/StabilityAIImageInterface.js.map +1 -1
  88. package/SubscriptionConfigBuilder.d.ts +6 -1
  89. package/SubscriptionConfigBuilder.js +22 -0
  90. package/SubscriptionConfigBuilder.js.map +1 -1
  91. package/SubscriptionConfiguration.d.ts +266 -169
  92. package/SubscriptionConfiguration.js +101 -79
  93. package/SubscriptionConfiguration.js.map +1 -1
  94. package/SubscriptionController.d.ts +2 -1
  95. package/SubscriptionController.js +643 -650
  96. package/SubscriptionController.js.map +1 -1
  97. package/SystemNotificationMessenger.d.ts +21 -4
  98. package/SystemNotificationMessenger.js +36 -30
  99. package/SystemNotificationMessenger.js.map +1 -1
  100. package/TestUtils.d.ts +9 -1
  101. package/TestUtils.js +105 -129
  102. package/TestUtils.js.map +1 -1
  103. package/Utils.d.ts +2 -16
  104. package/Utils.js +21 -22
  105. package/Utils.js.map +1 -1
  106. package/crud/CrudHelpers.js +17 -26
  107. package/crud/CrudHelpers.js.map +1 -1
  108. package/crud/CrudRecordsController.d.ts +1 -1
  109. package/crud/CrudRecordsController.js +259 -267
  110. package/crud/CrudRecordsController.js.map +1 -1
  111. package/crud/CrudRecordsControllerTests.js +174 -185
  112. package/crud/CrudRecordsControllerTests.js.map +1 -1
  113. package/crud/CrudRecordsStore.d.ts +7 -3
  114. package/crud/MemoryCrudRecordsStore.d.ts +4 -4
  115. package/crud/MemoryCrudRecordsStore.js +98 -118
  116. package/crud/MemoryCrudRecordsStore.js.map +1 -1
  117. package/crud/sub/MemorySubCrudRecordsStore.d.ts +24 -0
  118. package/crud/sub/MemorySubCrudRecordsStore.js +146 -0
  119. package/crud/sub/MemorySubCrudRecordsStore.js.map +1 -0
  120. package/crud/sub/SubCrudRecordsController.d.ts +182 -0
  121. package/crud/sub/SubCrudRecordsController.js +360 -0
  122. package/crud/sub/SubCrudRecordsController.js.map +1 -0
  123. package/crud/sub/SubCrudRecordsControllerTests.d.ts +39 -0
  124. package/crud/sub/SubCrudRecordsControllerTests.js +821 -0
  125. package/crud/sub/SubCrudRecordsControllerTests.js.map +1 -0
  126. package/crud/sub/SubCrudRecordsStore.d.ts +95 -0
  127. package/{forms/index.js → crud/sub/SubCrudRecordsStore.js} +2 -2
  128. package/crud/sub/SubCrudRecordsStore.js.map +1 -0
  129. package/crud/sub/index.d.ts +3 -0
  130. package/crud/sub/index.js +20 -0
  131. package/{forms → crud/sub}/index.js.map +1 -1
  132. package/index.d.ts +1 -1
  133. package/index.js +1 -1
  134. package/index.js.map +1 -1
  135. package/notifications/MemoryNotificationRecordsStore.js +189 -198
  136. package/notifications/MemoryNotificationRecordsStore.js.map +1 -1
  137. package/notifications/NotificationRecordsController.js +438 -460
  138. package/notifications/NotificationRecordsController.js.map +1 -1
  139. package/notifications/NotificationRecordsStore.d.ts +2 -1
  140. package/notifications/WebPushInterface.d.ts +0 -1
  141. package/notifications/WebPushInterface.js +0 -1
  142. package/notifications/WebPushInterface.js.map +1 -1
  143. package/package.json +6 -6
  144. package/packages/MemoryPackageRecordsStore.d.ts +10 -0
  145. package/packages/MemoryPackageRecordsStore.js +38 -0
  146. package/packages/MemoryPackageRecordsStore.js.map +1 -0
  147. package/packages/PackageRecordsController.d.ts +26 -0
  148. package/packages/PackageRecordsController.js +49 -0
  149. package/packages/PackageRecordsController.js.map +1 -0
  150. package/packages/PackageRecordsStore.d.ts +32 -0
  151. package/packages/PackageRecordsStore.js +19 -0
  152. package/packages/PackageRecordsStore.js.map +1 -0
  153. package/packages/index.d.ts +4 -0
  154. package/packages/index.js +21 -0
  155. package/packages/index.js.map +1 -0
  156. package/packages/version/MemoryPackageVersionRecordsStore.d.ts +21 -0
  157. package/packages/version/MemoryPackageVersionRecordsStore.js +177 -0
  158. package/packages/version/MemoryPackageVersionRecordsStore.js.map +1 -0
  159. package/packages/version/PackageVersionRecordsController.d.ts +144 -0
  160. package/packages/version/PackageVersionRecordsController.js +656 -0
  161. package/packages/version/PackageVersionRecordsController.js.map +1 -0
  162. package/packages/version/PackageVersionRecordsStore.d.ts +342 -0
  163. package/packages/version/PackageVersionRecordsStore.js +126 -0
  164. package/packages/version/PackageVersionRecordsStore.js.map +1 -0
  165. package/packages/version/index.d.ts +4 -0
  166. package/packages/version/index.js +21 -0
  167. package/packages/version/index.js.map +1 -0
  168. package/tracing/TracingDecorators.js +31 -40
  169. package/tracing/TracingDecorators.js.map +1 -1
  170. package/webhooks/MemoryWebhookRecordsStore.js +56 -72
  171. package/webhooks/MemoryWebhookRecordsStore.js.map +1 -1
  172. package/webhooks/WebhookEnvironment.d.ts +3 -3
  173. package/webhooks/WebhookRecordsController.d.ts +2 -1
  174. package/webhooks/WebhookRecordsController.js +389 -382
  175. package/webhooks/WebhookRecordsController.js.map +1 -1
  176. package/webhooks/WebhookRecordsStore.d.ts +2 -1
  177. package/websockets/InstRecordsStore.d.ts +50 -0
  178. package/websockets/InstRecordsStore.js +17 -0
  179. package/websockets/InstRecordsStore.js.map +1 -1
  180. package/websockets/MemoryTempInstRecordsStore.d.ts +5 -0
  181. package/websockets/MemoryTempInstRecordsStore.js +168 -179
  182. package/websockets/MemoryTempInstRecordsStore.js.map +1 -1
  183. package/websockets/MemoryWebsocketConnectionStore.js +98 -135
  184. package/websockets/MemoryWebsocketConnectionStore.js.map +1 -1
  185. package/websockets/MemoryWebsocketMessenger.js +29 -48
  186. package/websockets/MemoryWebsocketMessenger.js.map +1 -1
  187. package/websockets/SplitInstRecordsStore.d.ts +4 -1
  188. package/websockets/SplitInstRecordsStore.js +167 -185
  189. package/websockets/SplitInstRecordsStore.js.map +1 -1
  190. package/websockets/TemporaryInstRecordsStore.d.ts +19 -1
  191. package/websockets/TemporaryInstRecordsStore.js +17 -0
  192. package/websockets/TemporaryInstRecordsStore.js.map +1 -1
  193. package/websockets/WebsocketController.d.ts +147 -3
  194. package/websockets/WebsocketController.js +1735 -1391
  195. package/websockets/WebsocketController.js.map +1 -1
  196. package/websockets/index.d.ts +0 -1
  197. package/websockets/index.js +0 -1
  198. package/websockets/index.js.map +1 -1
  199. package/AAGUID.d.ts +0 -11
  200. package/AAGUID.js +0 -116
  201. package/AAGUID.js.map +0 -1
  202. package/AuthUtils.d.ts +0 -162
  203. package/AuthUtils.js +0 -327
  204. package/AuthUtils.js.map +0 -1
  205. package/forms/FormError.d.ts +0 -43
  206. package/forms/FormError.js +0 -56
  207. package/forms/FormError.js.map +0 -1
  208. package/forms/index.d.ts +0 -2
  209. package/websockets/Utils.d.ts +0 -33
  210. package/websockets/Utils.js +0 -82
  211. package/websockets/Utils.js.map +0 -1
@@ -4,22 +4,12 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9
- return new (P || (P = Promise))(function (resolve, reject) {
10
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13
- step((generator = generator.apply(thisArg, _arguments || [])).next());
14
- });
15
- };
16
- import { DEFAULT_BRANCH_NAME, } from '@casual-simulation/aux-common';
17
- import { CrudRecordsController, } from '../crud/CrudRecordsController';
7
+ import { DEFAULT_BRANCH_NAME, tryParseJson, } from '@casual-simulation/aux-common';
8
+ import { CrudRecordsController } from '../crud/CrudRecordsController';
18
9
  import { getWebhookFeatures } from '../SubscriptionConfiguration';
19
10
  import { traced } from '../tracing/TracingDecorators';
20
11
  import { SpanStatusCode, trace } from '@opentelemetry/api';
21
- import { STORED_AUX_SCHEMA, } from './WebhookEnvironment';
22
- import { tryParseJson } from '../Utils';
12
+ import { STORED_AUX_SCHEMA } from './WebhookEnvironment';
23
13
  import { v7 as uuidv7 } from 'uuid';
24
14
  import stringify from '@casual-simulation/fast-json-stable-stringify';
25
15
  import { sha256 } from 'hash.js';
@@ -34,7 +24,11 @@ export class WebhookRecordsController extends CrudRecordsController {
34
24
  return this._websockets;
35
25
  }
36
26
  constructor(config) {
37
- super(Object.assign(Object.assign({}, config), { resourceKind: 'webhook', name: 'WebhookRecordsController' }));
27
+ super({
28
+ ...config,
29
+ resourceKind: 'webhook',
30
+ name: 'WebhookRecordsController',
31
+ });
38
32
  this._environment = config.environment;
39
33
  this._data = config.data;
40
34
  this._files = config.files;
@@ -45,433 +39,446 @@ export class WebhookRecordsController extends CrudRecordsController {
45
39
  * Handles a webhook request.
46
40
  * @param request The request to handle.
47
41
  */
48
- handleWebhook(request) {
49
- var _a, _b, _c, _d, _e;
50
- return __awaiter(this, void 0, void 0, function* () {
51
- try {
52
- const requestTimeMs = Date.now();
53
- const webhookContext = yield this.policies.constructAuthorizationContext({
54
- recordKeyOrRecordName: request.recordName,
55
- userId: request.userId,
56
- });
57
- if (webhookContext.success === false) {
58
- return webhookContext;
59
- }
60
- const recordName = webhookContext.context.recordName;
61
- const webhook = yield this.store.getItemByAddress(recordName, request.address);
62
- if (!webhook) {
42
+ async handleWebhook(request) {
43
+ var _a, _b, _c, _d, _e, _f, _g;
44
+ try {
45
+ const requestTimeMs = Date.now();
46
+ const webhookContext = await this.policies.constructAuthorizationContext({
47
+ recordKeyOrRecordName: request.recordName,
48
+ userId: request.userId,
49
+ });
50
+ if (webhookContext.success === false) {
51
+ return webhookContext;
52
+ }
53
+ const recordName = webhookContext.context.recordName;
54
+ const webhook = await this.store.getItemByAddress(recordName, request.address);
55
+ if (!webhook) {
56
+ return {
57
+ success: false,
58
+ errorCode: 'not_found',
59
+ errorMessage: 'Webhook not found.',
60
+ };
61
+ }
62
+ const webhookAuthorization = await this.policies.authorizeUserAndInstancesForResources(webhookContext.context, {
63
+ instances: request.instances,
64
+ userId: request.userId,
65
+ resources: [
66
+ {
67
+ resourceKind: 'webhook',
68
+ resourceId: webhook.address,
69
+ action: 'run',
70
+ markers: webhook.markers,
71
+ },
72
+ ],
73
+ });
74
+ if (webhookAuthorization.success === false) {
75
+ return webhookAuthorization;
76
+ }
77
+ const checkMetrics = await this._checkSubscriptionMetrics('run', webhookContext.context, webhookAuthorization, webhook);
78
+ if (checkMetrics.success === false) {
79
+ return checkMetrics;
80
+ }
81
+ let state;
82
+ const stateRecordName = webhook.targetRecordName;
83
+ let stateInstName = undefined;
84
+ if (webhook.targetResourceKind === 'data') {
85
+ if (!webhook.targetRecordName) {
63
86
  return {
64
87
  success: false,
65
- errorCode: 'not_found',
66
- errorMessage: 'Webhook not found.',
88
+ errorCode: 'invalid_webhook_target',
89
+ errorMessage: 'Invalid webhook target. The targeted record does not contain a valid name.',
67
90
  };
68
91
  }
69
- const webhookAuthorization = yield this.policies.authorizeUserAndInstancesForResources(webhookContext.context, {
70
- instances: request.instances,
71
- userId: request.userId,
72
- resources: [
73
- {
74
- resourceKind: 'webhook',
75
- resourceId: webhook.address,
76
- action: 'run',
77
- markers: webhook.markers,
78
- },
79
- ],
80
- });
81
- if (webhookAuthorization.success === false) {
82
- return webhookAuthorization;
83
- }
84
- const checkMetrics = yield this._checkSubscriptionMetrics('run', webhookContext.context, webhookAuthorization, webhook);
85
- if (checkMetrics.success === false) {
86
- return checkMetrics;
87
- }
88
- let state = null;
89
- const stateRecordName = webhook.targetRecordName;
90
- let stateInstName = undefined;
91
- if (webhook.targetResourceKind === 'data') {
92
- const data = yield this._data.getData(webhook.targetRecordName, webhook.targetAddress, webhook.userId, request.instances);
93
- if (data.success === false) {
94
- return {
95
- success: false,
96
- errorCode: 'invalid_webhook_target',
97
- errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
98
- internalError: data,
99
- };
100
- }
101
- let auxData;
102
- if (typeof data.data === 'string') {
103
- const stored = tryParseJson(data.data);
104
- if (stored.success === true) {
105
- auxData = stored.value;
106
- }
107
- }
108
- else if (typeof data.data === 'object') {
109
- auxData = data.data;
110
- }
111
- const parseResult = STORED_AUX_SCHEMA.safeParse(auxData);
112
- if (parseResult.success === false) {
113
- return {
114
- success: false,
115
- errorCode: 'invalid_webhook_target',
116
- errorMessage: 'Invalid webhook target. The targeted record does not contain valid data.',
117
- internalError: {
118
- success: false,
119
- errorCode: 'unacceptable_request',
120
- errorMessage: 'The data record does not contain valid AUX data.',
121
- issues: parseResult.error.issues,
122
- },
123
- };
124
- }
125
- state = {
126
- type: 'aux',
127
- state: parseResult.data,
92
+ const data = await this._data.getData(webhook.targetRecordName, webhook.targetAddress, webhook.userId, request.instances);
93
+ if (data.success === false) {
94
+ return {
95
+ success: false,
96
+ errorCode: 'invalid_webhook_target',
97
+ errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
98
+ internalError: data,
128
99
  };
129
100
  }
130
- else if (webhook.targetResourceKind === 'file') {
131
- const file = yield this._files.readFile(webhook.targetRecordName, webhook.targetAddress, webhook.userId, request.instances);
132
- if (file.success === false) {
133
- return {
134
- success: false,
135
- errorCode: 'invalid_webhook_target',
136
- errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
137
- internalError: file,
138
- };
101
+ let auxData;
102
+ if (typeof data.data === 'string') {
103
+ const stored = tryParseJson(data.data);
104
+ if (stored.success === true) {
105
+ auxData = stored.value;
139
106
  }
140
- state = {
141
- type: 'url',
142
- requestUrl: file.requestUrl,
143
- requestMethod: file.requestMethod,
144
- requestHeaders: file.requestHeaders,
145
- };
146
107
  }
147
- else if (webhook.targetResourceKind === 'inst') {
148
- if (!this._websockets) {
149
- return {
150
- success: false,
151
- errorCode: 'invalid_webhook_target',
152
- errorMessage: 'Invalid webhook target. Inst records are not supported in this environment.',
153
- internalError: {
154
- success: false,
155
- errorCode: 'not_supported',
156
- errorMessage: 'Inst records are not supported in this environment.',
157
- },
158
- };
159
- }
160
- const inst = yield this._websockets.getBranchData(webhook.userId, webhook.targetRecordName, webhook.targetAddress, DEFAULT_BRANCH_NAME, 2);
161
- if (inst.success === false) {
162
- return {
163
- success: false,
164
- errorCode: 'invalid_webhook_target',
165
- errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
166
- internalError: inst,
167
- };
168
- }
169
- stateInstName = webhook.targetAddress;
170
- state = {
171
- type: 'aux',
172
- state: inst.data,
173
- };
108
+ else if (typeof data.data === 'object') {
109
+ auxData = data.data;
174
110
  }
175
- if (!state) {
111
+ const parseResult = STORED_AUX_SCHEMA.safeParse(auxData);
112
+ if (parseResult.success === false) {
176
113
  return {
177
114
  success: false,
178
115
  errorCode: 'invalid_webhook_target',
179
- errorMessage: 'Invalid webhook target. The targeted record does not contain a valid AUX.',
116
+ errorMessage: 'Invalid webhook target. The targeted record does not contain valid data.',
117
+ internalError: {
118
+ success: false,
119
+ errorCode: 'unacceptable_request',
120
+ errorMessage: 'The data record does not contain valid AUX data.',
121
+ issues: parseResult.error.issues,
122
+ },
180
123
  };
181
124
  }
182
- let sessionUserId;
183
- let sessionKey;
184
- let connectionKey;
185
- if (webhook.userId) {
186
- // Create a session for the user
187
- const issueSessionResult = yield this._auth.issueSession({
188
- userId: webhook.userId,
189
- requestingUserId: null,
190
- requestingUserRole: 'system',
191
- ipAddress: null,
192
- lifetimeMs: (_a = checkMetrics.features.tokenLifetimeMs) !== null && _a !== void 0 ? _a : 5 * 60 * 1000,
193
- });
194
- if (issueSessionResult.success === true) {
195
- sessionUserId = issueSessionResult.userId;
196
- sessionKey = issueSessionResult.sessionKey;
197
- connectionKey = issueSessionResult.connectionKey;
198
- }
199
- else {
200
- console.warn('[WebhookRecordsController] Error issuing session for webhook:', issueSessionResult);
201
- }
202
- }
203
- const options = {
204
- initTimeoutMs: (_b = checkMetrics.features.initTimeoutMs) !== null && _b !== void 0 ? _b : 5000,
205
- requestTimeoutMs: (_c = checkMetrics.features.requestTimeoutMs) !== null && _c !== void 0 ? _c : 5000,
206
- fetchTimeoutMs: (_d = checkMetrics.features.fetchTimeoutMs) !== null && _d !== void 0 ? _d : 5000,
207
- addStateTimeoutMs: (_e = checkMetrics.features.addStateTimeoutMs) !== null && _e !== void 0 ? _e : 1000,
125
+ state = {
126
+ type: 'aux',
127
+ state: parseResult.data,
208
128
  };
209
- const result = yield this._environment.handleHttpRequest({
210
- state: state,
211
- recordName: stateRecordName,
212
- inst: stateInstName,
213
- request: request.request,
214
- requestUserId: request.userId,
215
- sessionUserId,
216
- sessionKey,
217
- connectionKey,
218
- options,
219
- });
220
- const responseTimeMs = Date.now();
221
- const stateHash = getHash(state);
222
- const runId = uuidv7();
223
- let infoFileName = null;
224
- let infoRecordName = null;
225
- if (webhook.userId) {
226
- const recordName = webhook.userId;
227
- const dataFile = {
228
- runId,
229
- version: 1,
230
- request: request.request,
231
- requestUserId: request.userId,
232
- response: result.success === true ? result.response : null,
233
- logs: result.success === true ? result.logs : [],
234
- state,
235
- stateSha256: stateHash,
236
- authorization: webhookAuthorization,
129
+ }
130
+ else if (webhook.targetResourceKind === 'file') {
131
+ if (!webhook.targetRecordName) {
132
+ return {
133
+ success: false,
134
+ errorCode: 'invalid_webhook_target',
135
+ errorMessage: 'Invalid webhook target. The targeted record does not contain a valid name.',
237
136
  };
238
- const json = stringify(dataFile);
239
- const data = new TextEncoder().encode(json);
240
- const recordResult = yield this._files.recordFile(recordName, recordName, {
241
- fileSha256Hex: sha256().update(data).digest('hex'),
242
- fileByteLength: data.byteLength,
243
- fileDescription: `Webhook data for run ${runId}`,
244
- fileMimeType: 'application/json',
245
- headers: {},
246
- markers: [`private:logs`],
247
- });
248
- if (recordResult.success === false) {
249
- console.error('[WebhookRecordsController] Error recording webhook info file:', recordResult);
250
- }
251
- else {
252
- infoRecordName = recordName;
253
- infoFileName = recordResult.fileName;
254
- const requestResult = yield axios.request({
255
- method: recordResult.uploadMethod,
256
- headers: recordResult.uploadHeaders,
257
- url: recordResult.uploadUrl,
258
- data: data,
259
- validateStatus: () => true,
260
- });
261
- if (requestResult.status <= 199 ||
262
- requestResult.status >= 300) {
263
- console.error('[WebhookRecordsController] Error uploading webhook info file:', requestResult);
264
- }
265
- }
266
137
  }
267
- const run = {
268
- runId: uuidv7(),
269
- recordName: recordName,
270
- webhookAddress: request.address,
271
- errorResult: result.success === false ? result : null,
272
- requestTimeMs,
273
- responseTimeMs,
274
- statusCode: result.success === true ? result.response.statusCode : null,
275
- stateSha256: stateHash,
276
- infoRecordName,
277
- infoFileName,
278
- options,
279
- };
280
- yield this.store.recordWebhookRun(run);
281
- if (result.success === true) {
138
+ const file = await this._files.readFile(webhook.targetRecordName, webhook.targetAddress, (_a = webhook.userId) !== null && _a !== void 0 ? _a : null, request.instances);
139
+ if (file.success === false) {
282
140
  return {
283
- success: true,
284
- response: result.response,
141
+ success: false,
142
+ errorCode: 'invalid_webhook_target',
143
+ errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
144
+ internalError: file,
285
145
  };
286
146
  }
287
- else {
288
- return result;
289
- }
290
- }
291
- catch (err) {
292
- const span = trace.getActiveSpan();
293
- span === null || span === void 0 ? void 0 : span.recordException(err);
294
- span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
295
- console.error('[WebhookRecordsController] Error handling webhook:', err);
296
- return {
297
- success: false,
298
- errorCode: 'server_error',
299
- errorMessage: 'A server error occurred.',
147
+ state = {
148
+ type: 'url',
149
+ requestUrl: file.requestUrl,
150
+ requestMethod: file.requestMethod,
151
+ requestHeaders: file.requestHeaders,
300
152
  };
301
153
  }
302
- });
303
- }
304
- listWebhookRuns(request) {
305
- return __awaiter(this, void 0, void 0, function* () {
306
- try {
307
- const context = yield this.policies.constructAuthorizationContext({
308
- userId: request.userId,
309
- recordKeyOrRecordName: request.recordName,
310
- });
311
- if (context.success === false) {
312
- return context;
313
- }
314
- const recordName = context.context.recordName;
315
- const webhook = yield this.store.getItemByAddress(recordName, request.address);
316
- if (!webhook) {
154
+ else if (webhook.targetResourceKind === 'inst') {
155
+ if (!this._websockets) {
317
156
  return {
318
157
  success: false,
319
- errorCode: 'data_not_found',
320
- errorMessage: 'The webhook was not found.',
158
+ errorCode: 'invalid_webhook_target',
159
+ errorMessage: 'Invalid webhook target. Inst records are not supported in this environment.',
160
+ internalError: {
161
+ success: false,
162
+ errorCode: 'not_supported',
163
+ errorMessage: 'Inst records are not supported in this environment.',
164
+ },
321
165
  };
322
166
  }
323
- const authorization = yield this.policies.authorizeUserAndInstancesForResources(context.context, {
324
- instances: request.instances,
325
- userId: context.context.userId,
326
- resources: [
327
- {
328
- resourceKind: 'webhook',
329
- resourceId: webhook.address,
330
- action: 'read',
331
- markers: webhook.markers,
332
- },
333
- ],
334
- });
335
- if (authorization.success === false) {
336
- return authorization;
167
+ const inst = await this._websockets.getBranchData((_b = webhook.userId) !== null && _b !== void 0 ? _b : null, webhook.targetRecordName, webhook.targetAddress, DEFAULT_BRANCH_NAME, 2);
168
+ if (inst.success === false) {
169
+ return {
170
+ success: false,
171
+ errorCode: 'invalid_webhook_target',
172
+ errorMessage: 'Invalid webhook target. The targeted record was not able to be retrieved.',
173
+ internalError: inst,
174
+ };
337
175
  }
338
- const runs = yield this.store.listWebhookRunsForWebhook(recordName, request.address, request.requestTimeMs);
339
- return {
340
- success: true,
341
- recordName: recordName,
342
- items: runs.items,
343
- totalCount: runs.totalCount,
344
- marker: runs.marker,
176
+ stateInstName = webhook.targetAddress;
177
+ state = {
178
+ type: 'aux',
179
+ state: inst.data,
345
180
  };
346
181
  }
347
- catch (err) {
348
- const span = trace.getActiveSpan();
349
- span === null || span === void 0 ? void 0 : span.recordException(err);
350
- span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
351
- console.error('[WebhookRecordsController] Error listing webhook runs:', err);
182
+ else {
352
183
  return {
353
184
  success: false,
354
- errorCode: 'server_error',
355
- errorMessage: 'A server error occurred.',
185
+ errorCode: 'invalid_webhook_target',
186
+ errorMessage: 'Invalid webhook target. The targeted record does not contain a valid AUX.',
356
187
  };
357
188
  }
358
- });
359
- }
360
- getWebhookRun(request) {
361
- return __awaiter(this, void 0, void 0, function* () {
362
- try {
363
- const run = yield this.store.getWebhookRunInfo(request.runId);
364
- if (!run) {
365
- return {
366
- success: false,
367
- errorCode: 'data_not_found',
368
- errorMessage: 'The webhook run was not found.',
369
- };
370
- }
371
- const context = yield this.policies.constructAuthorizationContext({
372
- userId: request.userId,
373
- recordKeyOrRecordName: run.run.recordName,
189
+ let sessionUserId = undefined;
190
+ let sessionKey = undefined;
191
+ let connectionKey = undefined;
192
+ if (webhook.userId) {
193
+ // Create a session for the user
194
+ const issueSessionResult = await this._auth.issueSession({
195
+ userId: webhook.userId,
196
+ requestingUserId: null,
197
+ requestingUserRole: 'system',
198
+ ipAddress: null,
199
+ lifetimeMs: (_c = checkMetrics.features.tokenLifetimeMs) !== null && _c !== void 0 ? _c : 5 * 60 * 1000,
374
200
  });
375
- if (context.success === false) {
376
- return context;
201
+ if (issueSessionResult.success === true) {
202
+ sessionUserId = issueSessionResult.userId;
203
+ sessionKey = issueSessionResult.sessionKey;
204
+ connectionKey = issueSessionResult.connectionKey;
205
+ }
206
+ else {
207
+ console.warn('[WebhookRecordsController] Error issuing session for webhook:', issueSessionResult);
377
208
  }
378
- const authorization = yield this.policies.authorizeUserAndInstances(context.context, {
379
- action: 'read',
380
- resourceKind: 'webhook',
381
- resourceId: run.webhook.address,
382
- markers: run.webhook.markers,
383
- instances: request.instances,
384
- userId: context.context.userId,
209
+ }
210
+ const options = {
211
+ initTimeoutMs: (_d = checkMetrics.features.initTimeoutMs) !== null && _d !== void 0 ? _d : 5000,
212
+ requestTimeoutMs: (_e = checkMetrics.features.requestTimeoutMs) !== null && _e !== void 0 ? _e : 5000,
213
+ fetchTimeoutMs: (_f = checkMetrics.features.fetchTimeoutMs) !== null && _f !== void 0 ? _f : 5000,
214
+ addStateTimeoutMs: (_g = checkMetrics.features.addStateTimeoutMs) !== null && _g !== void 0 ? _g : 1000,
215
+ };
216
+ const result = await this._environment.handleHttpRequest({
217
+ state: state,
218
+ recordName: stateRecordName,
219
+ inst: stateInstName,
220
+ request: request.request,
221
+ requestUserId: request.userId,
222
+ sessionUserId,
223
+ sessionKey,
224
+ connectionKey,
225
+ options,
226
+ });
227
+ const responseTimeMs = Date.now();
228
+ const stateHash = getHash(state);
229
+ const runId = uuidv7();
230
+ let infoFileName = null;
231
+ let infoRecordName = null;
232
+ if (webhook.userId) {
233
+ const recordName = webhook.userId;
234
+ const dataFile = {
235
+ runId,
236
+ version: 1,
237
+ request: request.request,
238
+ requestUserId: request.userId,
239
+ response: result.success === true ? result.response : null,
240
+ logs: result.success === true ? result.logs : [],
241
+ state,
242
+ stateSha256: stateHash,
243
+ authorization: webhookAuthorization,
244
+ };
245
+ const json = stringify(dataFile);
246
+ const data = new TextEncoder().encode(json);
247
+ const recordResult = await this._files.recordFile(recordName, recordName, {
248
+ fileSha256Hex: sha256().update(data).digest('hex'),
249
+ fileByteLength: data.byteLength,
250
+ fileDescription: `Webhook data for run ${runId}`,
251
+ fileMimeType: 'application/json',
252
+ headers: {},
253
+ markers: [`private:logs`],
385
254
  });
386
- if (authorization.success === false) {
387
- return authorization;
255
+ if (recordResult.success === false) {
256
+ console.error('[WebhookRecordsController] Error recording webhook info file:', recordResult);
388
257
  }
389
- let infoFileResult = null;
390
- if (run.run.infoRecordName && run.run.infoFileName) {
391
- infoFileResult = yield this._files.readFile(run.run.infoRecordName, run.run.infoFileName, run.webhook.userId, request.instances);
258
+ else {
259
+ infoRecordName = recordName;
260
+ infoFileName = recordResult.fileName;
261
+ const requestResult = await axios.request({
262
+ method: recordResult.uploadMethod,
263
+ headers: recordResult.uploadHeaders,
264
+ url: recordResult.uploadUrl,
265
+ data: data,
266
+ validateStatus: () => true,
267
+ });
268
+ if (requestResult.status <= 199 ||
269
+ requestResult.status >= 300) {
270
+ console.error('[WebhookRecordsController] Error uploading webhook info file:', requestResult);
271
+ }
392
272
  }
273
+ }
274
+ const run = {
275
+ runId: uuidv7(),
276
+ recordName: recordName,
277
+ webhookAddress: request.address,
278
+ errorResult: result.success === false ? result : null,
279
+ requestTimeMs,
280
+ responseTimeMs,
281
+ statusCode: result.success === true ? result.response.statusCode : null,
282
+ stateSha256: stateHash,
283
+ infoRecordName,
284
+ infoFileName,
285
+ options,
286
+ };
287
+ await this.store.recordWebhookRun(run);
288
+ if (result.success === true) {
393
289
  return {
394
290
  success: true,
395
- run: run.run,
396
- infoFileResult,
291
+ response: result.response,
397
292
  };
398
293
  }
399
- catch (err) {
400
- const span = trace.getActiveSpan();
294
+ else {
295
+ return result;
296
+ }
297
+ }
298
+ catch (err) {
299
+ const span = trace.getActiveSpan();
300
+ if (err instanceof Error) {
401
301
  span === null || span === void 0 ? void 0 : span.recordException(err);
402
- span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
403
- console.error('[WebhookRecordsController] Error getting webhook run:', err);
302
+ }
303
+ span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
304
+ console.error('[WebhookRecordsController] Error handling webhook:', err);
305
+ return {
306
+ success: false,
307
+ errorCode: 'server_error',
308
+ errorMessage: 'A server error occurred.',
309
+ };
310
+ }
311
+ }
312
+ async listWebhookRuns(request) {
313
+ try {
314
+ const context = await this.policies.constructAuthorizationContext({
315
+ userId: request.userId,
316
+ recordKeyOrRecordName: request.recordName,
317
+ });
318
+ if (context.success === false) {
319
+ return context;
320
+ }
321
+ const recordName = context.context.recordName;
322
+ const webhook = await this.store.getItemByAddress(recordName, request.address);
323
+ if (!webhook) {
404
324
  return {
405
325
  success: false,
406
- errorCode: 'server_error',
407
- errorMessage: 'A server error occurred.',
326
+ errorCode: 'data_not_found',
327
+ errorMessage: 'The webhook was not found.',
408
328
  };
409
329
  }
410
- });
411
- }
412
- _checkSubscriptionMetrics(action, context, authorization, item) {
413
- return __awaiter(this, void 0, void 0, function* () {
414
- const config = yield this.config.getSubscriptionConfiguration();
415
- const metrics = yield this.store.getSubscriptionMetrics({
416
- ownerId: context.recordOwnerId,
417
- studioId: context.recordStudioId,
330
+ const authorization = await this.policies.authorizeUserAndInstancesForResources(context.context, {
331
+ instances: request.instances,
332
+ userId: context.context.userId,
333
+ resources: [
334
+ {
335
+ resourceKind: 'webhook',
336
+ resourceId: webhook.address,
337
+ action: 'read',
338
+ markers: webhook.markers,
339
+ },
340
+ ],
418
341
  });
419
- const features = getWebhookFeatures(config, metrics.subscriptionStatus, metrics.subscriptionId, metrics.subscriptionType);
420
- if (!features.allowed) {
342
+ if (authorization.success === false) {
343
+ return authorization;
344
+ }
345
+ const runs = await this.store.listWebhookRunsForWebhook(recordName, request.address, request.requestTimeMs);
346
+ return {
347
+ success: true,
348
+ recordName: recordName,
349
+ items: runs.items,
350
+ totalCount: runs.totalCount,
351
+ marker: runs.marker,
352
+ };
353
+ }
354
+ catch (err) {
355
+ const span = trace.getActiveSpan();
356
+ if (err instanceof Error) {
357
+ span === null || span === void 0 ? void 0 : span.recordException(err);
358
+ }
359
+ span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
360
+ console.error('[WebhookRecordsController] Error listing webhook runs:', err);
361
+ return {
362
+ success: false,
363
+ errorCode: 'server_error',
364
+ errorMessage: 'A server error occurred.',
365
+ };
366
+ }
367
+ }
368
+ async getWebhookRun(request) {
369
+ var _a;
370
+ try {
371
+ const run = await this.store.getWebhookRunInfo(request.runId);
372
+ if (!run) {
421
373
  return {
422
374
  success: false,
423
- errorCode: 'not_authorized',
424
- errorMessage: 'Webhooks are not allowed for this subscription.',
375
+ errorCode: 'data_not_found',
376
+ errorMessage: 'The webhook run was not found.',
425
377
  };
426
378
  }
427
- if (action === 'create' && typeof features.maxItems === 'number') {
428
- if (metrics.totalItems >= features.maxItems) {
429
- return {
430
- success: false,
431
- errorCode: 'subscription_limit_reached',
432
- errorMessage: 'The maximum number of webhook items has been reached for your subscription.',
433
- };
434
- }
379
+ const context = await this.policies.constructAuthorizationContext({
380
+ userId: request.userId,
381
+ recordKeyOrRecordName: run.run.recordName,
382
+ });
383
+ if (context.success === false) {
384
+ return context;
435
385
  }
436
- if (action === 'create') {
437
- // create a user for the webhook
438
- if (!item.userId) {
439
- const result = yield this._auth.createAccount({
440
- userRole: 'superUser', // The system gets superUser permissions when performing administrative tasks
441
- ipAddress: null,
442
- createSession: false,
443
- });
444
- if (result.success === false) {
445
- return result;
446
- }
447
- else {
448
- item.userId = result.userId;
449
- }
450
- }
386
+ const authorization = await this.policies.authorizeUserAndInstances(context.context, {
387
+ action: 'read',
388
+ resourceKind: 'webhook',
389
+ resourceId: run.webhook.address,
390
+ markers: run.webhook.markers,
391
+ instances: request.instances,
392
+ userId: context.context.userId,
393
+ });
394
+ if (authorization.success === false) {
395
+ return authorization;
451
396
  }
452
- if (action === 'run') {
453
- if (typeof features.maxRunsPerPeriod === 'number' &&
454
- metrics.totalRunsInPeriod >= features.maxRunsPerPeriod) {
455
- return {
456
- success: false,
457
- errorCode: 'subscription_limit_reached',
458
- errorMessage: 'The maximum number of webhook runs has been reached for your subscription.',
459
- };
460
- }
461
- if (typeof features.maxRunsPerHour === 'number' &&
462
- metrics.totalRunsInLastHour >= features.maxRunsPerHour) {
463
- return {
464
- success: false,
465
- errorCode: 'subscription_limit_reached',
466
- errorMessage: 'The maximum number of webhook runs has been reached for your subscription.',
467
- };
468
- }
397
+ let infoFileResult = null;
398
+ if (run.run.infoRecordName && run.run.infoFileName) {
399
+ infoFileResult = await this._files.readFile(run.run.infoRecordName, run.run.infoFileName, (_a = run.webhook.userId) !== null && _a !== void 0 ? _a : null, request.instances);
469
400
  }
470
401
  return {
471
402
  success: true,
472
- features,
403
+ run: run.run,
404
+ infoFileResult,
405
+ };
406
+ }
407
+ catch (err) {
408
+ const span = trace.getActiveSpan();
409
+ if (err instanceof Error) {
410
+ span === null || span === void 0 ? void 0 : span.recordException(err);
411
+ }
412
+ span === null || span === void 0 ? void 0 : span.setStatus({ code: SpanStatusCode.ERROR });
413
+ console.error('[WebhookRecordsController] Error getting webhook run:', err);
414
+ return {
415
+ success: false,
416
+ errorCode: 'server_error',
417
+ errorMessage: 'A server error occurred.',
473
418
  };
419
+ }
420
+ }
421
+ async _checkSubscriptionMetrics(action, context, authorization, item) {
422
+ const config = await this.config.getSubscriptionConfiguration();
423
+ const metrics = await this.store.getSubscriptionMetrics({
424
+ ownerId: context.recordOwnerId,
425
+ studioId: context.recordStudioId,
474
426
  });
427
+ const features = getWebhookFeatures(config, metrics.subscriptionStatus, metrics.subscriptionId, metrics.subscriptionType);
428
+ if (!features.allowed) {
429
+ return {
430
+ success: false,
431
+ errorCode: 'not_authorized',
432
+ errorMessage: 'Webhooks are not allowed for this subscription.',
433
+ };
434
+ }
435
+ if (action === 'create' && typeof features.maxItems === 'number') {
436
+ if (metrics.totalItems >= features.maxItems) {
437
+ return {
438
+ success: false,
439
+ errorCode: 'subscription_limit_reached',
440
+ errorMessage: 'The maximum number of webhook items has been reached for your subscription.',
441
+ };
442
+ }
443
+ }
444
+ if (action === 'create') {
445
+ // create a user for the webhook
446
+ if (item && !item.userId) {
447
+ const result = await this._auth.createAccount({
448
+ userRole: 'superUser', // The system gets superUser permissions when performing administrative tasks
449
+ ipAddress: null,
450
+ createSession: false,
451
+ });
452
+ if (result.success === false) {
453
+ return result;
454
+ }
455
+ else {
456
+ item.userId = result.userId;
457
+ }
458
+ }
459
+ }
460
+ if (action === 'run') {
461
+ if (typeof features.maxRunsPerPeriod === 'number' &&
462
+ metrics.totalRunsInPeriod >= features.maxRunsPerPeriod) {
463
+ return {
464
+ success: false,
465
+ errorCode: 'subscription_limit_reached',
466
+ errorMessage: 'The maximum number of webhook runs has been reached for your subscription.',
467
+ };
468
+ }
469
+ if (typeof features.maxRunsPerHour === 'number' &&
470
+ metrics.totalRunsInLastHour >= features.maxRunsPerHour) {
471
+ return {
472
+ success: false,
473
+ errorCode: 'subscription_limit_reached',
474
+ errorMessage: 'The maximum number of webhook runs has been reached for your subscription.',
475
+ };
476
+ }
477
+ }
478
+ return {
479
+ success: true,
480
+ features,
481
+ };
475
482
  }
476
483
  _transformInputItem(item) {
477
484
  delete item.userId;