@getstrata/core 3.0.4 → 3.0.7

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 (103) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +17 -9
  3. package/dist/core/auth/policy.d.ts +4 -1
  4. package/dist/core/auth/saml/samlServiceProvider.d.ts +2 -3
  5. package/dist/core/cache/createCacheStore.d.ts +1 -1
  6. package/dist/core/cache/expiration.d.ts +2 -0
  7. package/dist/core/cache/redisCacheScript.d.ts +1 -1
  8. package/dist/core/cache/redisCacheStore.d.ts +5 -5
  9. package/dist/core/cache/repository.d.ts +2 -0
  10. package/dist/core/cache/simpleCache.d.ts +5 -5
  11. package/dist/core/cache/simpleCacheStore.d.ts +3 -3
  12. package/dist/core/cache/store.d.ts +5 -4
  13. package/dist/core/cache/taggedCache.d.ts +2 -0
  14. package/dist/core/cache/tokens.d.ts +1 -1
  15. package/dist/core/config/envSchema.d.ts +13 -0
  16. package/dist/core/contracts/application.d.ts +4 -0
  17. package/dist/core/contracts/di.d.ts +2 -2
  18. package/dist/core/contracts/provider.d.ts +13 -0
  19. package/dist/core/contracts/serviceTokens.d.ts +12 -11
  20. package/dist/core/database/factory.d.ts +3 -0
  21. package/dist/core/database/index.d.ts +1 -1
  22. package/dist/core/database/migrations/declaration.d.ts +11 -0
  23. package/dist/core/database/migrations/runner.d.ts +2 -0
  24. package/dist/core/database/model.d.ts +16 -3
  25. package/dist/core/database/modelQuery.d.ts +1 -10
  26. package/dist/core/database/modelRelationLoader.d.ts +31 -0
  27. package/dist/core/database/mysqlConnection.d.ts +2 -2
  28. package/dist/core/database/mysqlNative.d.ts +2 -0
  29. package/dist/core/database/ormRuntime.d.ts +1 -1
  30. package/dist/core/database/rawMysql.d.ts +1 -1
  31. package/dist/core/events/eventBusClass.d.ts +6 -3
  32. package/dist/core/events/index.d.ts +1 -1
  33. package/dist/core/http/formRequest.d.ts +2 -0
  34. package/dist/core/http/loginThrottleMiddleware.d.ts +1 -2
  35. package/dist/core/http/memoryThrottleMiddleware.d.ts +1 -3
  36. package/dist/core/http/webFormRequest.d.ts +3 -5
  37. package/dist/core/mail/mailer.d.ts +6 -3
  38. package/dist/core/mail/markdownMailable.d.ts +2 -2
  39. package/dist/core/notifications/dispatcher.d.ts +5 -5
  40. package/dist/core/notifications/index.d.ts +1 -1
  41. package/dist/core/notifications/types.d.ts +9 -2
  42. package/dist/core/queue/index.d.ts +8 -3
  43. package/dist/core/queue/queueHandoff.d.ts +2 -2
  44. package/dist/core/runtime/application.d.ts +2 -0
  45. package/dist/core/security/oauthState.d.ts +12 -2
  46. package/dist/core/security/safeUrl.d.ts +1 -11
  47. package/dist/core/storage/storage.d.ts +23 -6
  48. package/dist/core/testing.d.ts +5 -0
  49. package/dist/core/testingState.d.ts +22 -0
  50. package/dist/entries/audit/exportAuditLogs.js +1 -0
  51. package/dist/entries/auth/intendedUrlCookie.js +106 -18
  52. package/dist/entries/auth/jwt.js +68 -6
  53. package/dist/entries/auth/jwtGuard.js +76 -12
  54. package/dist/entries/auth/oauth/samlProvider.js +4 -5
  55. package/dist/entries/auth/passwordConfirmCookie.js +69 -3
  56. package/dist/entries/auth/saml/samlServiceProvider.js +5 -7
  57. package/dist/entries/auth/sessionCookie.js +69 -6
  58. package/dist/entries/auth/sessionGuard.js +69 -6
  59. package/dist/entries/cache/createCacheStore.js +45 -23
  60. package/dist/entries/cache/repository.js +20 -5
  61. package/dist/entries/cache/simpleCache.js +21 -7
  62. package/dist/entries/cache/simpleCacheStore.js +2 -3
  63. package/dist/entries/config/envSchema.js +13 -0
  64. package/dist/entries/contracts/serviceTokens.js +2 -0
  65. package/dist/entries/database/bindings.js +19 -95
  66. package/dist/entries/database/factory.js +4 -0
  67. package/dist/entries/database/migrations.js +714 -1
  68. package/dist/entries/database/ownedReadOnlyObservation.js +1 -5
  69. package/dist/entries/database/sqliteConnection.js +1 -5
  70. package/dist/entries/http/flashMiddleware.js +33 -14
  71. package/dist/entries/http/flashSession.js +33 -14
  72. package/dist/entries/http/formRequest.js +12 -6
  73. package/dist/entries/http/memoryThrottleMiddleware.js +12 -11
  74. package/dist/entries/http/pagination.js +4 -4
  75. package/dist/entries/http/parseMultipartUpload.js +62 -9
  76. package/dist/entries/http/requirePasswordConfirmMiddleware.js +5 -2
  77. package/dist/entries/http/requireWebAuthMiddleware.js +5 -2
  78. package/dist/entries/http/routeModelBinding.js +4 -4
  79. package/dist/entries/http/safeInternalPath.js +5 -2
  80. package/dist/entries/http/scimThrottleMiddleware.js +5 -2
  81. package/dist/entries/http/securedRouteModelBinding.js +4 -4
  82. package/dist/entries/http/throttleMiddleware.js +5 -2
  83. package/dist/entries/http/uploads.js +62 -9
  84. package/dist/entries/http/validation.js +4 -4
  85. package/dist/entries/http/webFormRequest.js +74 -95
  86. package/dist/entries/jobs/exportAuditLogsJob.js +9 -4
  87. package/dist/entries/jobs/invalidateCacheTagsJob.js +9 -4
  88. package/dist/entries/queue/createAppQueue.js +10 -5
  89. package/dist/entries/queue/publicQueue.js +10 -5
  90. package/dist/entries/queue/queueWorkerTransport.js +10 -5
  91. package/dist/entries/queue.js +9 -4
  92. package/dist/entries/runtime/application.js +50 -3
  93. package/dist/entries/security/oauthState.js +61 -2
  94. package/dist/entries/security/tokenExpiry.js +62 -9
  95. package/dist/entries/storage/storage.js +102 -1
  96. package/dist/entries/testing.js +18 -0
  97. package/dist/framework/public-api.d.ts +16 -13
  98. package/dist/index.js +380 -266
  99. package/dist/internal/mysqlNative.js +97 -0
  100. package/dist/internal/ormRuntime.js +41 -4
  101. package/dist/internal/testingState.js +31 -0
  102. package/dist/types/services.d.ts +8 -1
  103. package/package.json +17 -4
@@ -24,8 +24,8 @@ function parseOptionalPositiveIntQueryParam(params, name) {
24
24
  if (value === null || value.trim() === "") {
25
25
  return;
26
26
  }
27
- const parsed = Number.parseInt(value, 10);
28
- if (!Number.isInteger(parsed) || parsed <= 0) {
27
+ const parsed = Number(value);
28
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
29
29
  throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
30
30
  }
31
31
  return parsed;
@@ -121,8 +121,8 @@ function readOptionalPositiveInt(payload, field) {
121
121
  return readRequiredPositiveInt(payload, field);
122
122
  }
123
123
  function parsePositiveIntParam(value, name = "id") {
124
- const parsed = Number.parseInt(value, 10);
125
- if (!Number.isInteger(parsed) || parsed <= 0) {
124
+ const parsed = Number(value);
125
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
126
126
  throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
127
127
  }
128
128
  return parsed;
@@ -1,71 +1,10 @@
1
1
  // @bun
2
- // ../../src/core/http/webFormRequest.ts
3
- import { ForbiddenError, ValidationError } from "@getstrata/core/errors/http";
4
-
5
- // ../../src/core/http/contentNegotiation.ts
6
- function requestPrefersJson(request) {
7
- if (!request) {
8
- return true;
9
- }
10
- let pathname;
11
- try {
12
- pathname = new URL(request.url).pathname;
13
- } catch {
14
- return true;
15
- }
16
- if (request.headers.get("HX-Request") === "true") {
17
- return false;
18
- }
19
- if (pathname.startsWith("/api/")) {
20
- return true;
21
- }
22
- const accept = request.headers.get("accept")?.toLowerCase() ?? "";
23
- if (accept.includes("text/html")) {
24
- return false;
25
- }
26
- if (accept.includes("application/json")) {
27
- return true;
28
- }
29
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
30
- if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
31
- return false;
32
- }
33
- return false;
34
- }
35
-
36
- // ../../src/core/http/parseFormBody.ts
37
- import { BadRequestError } from "@getstrata/core/errors/http";
38
- async function parseFormBody(request, options = {}) {
39
- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
40
- if (!contentType.includes("application/x-www-form-urlencoded") && !contentType.includes("multipart/form-data")) {
41
- throw new BadRequestError("Expected a form submission.");
42
- }
43
- return formDataToRecord(await request.formData(), options);
44
- }
45
- function formDataToRecord(formData, options = {}) {
46
- if (options.preserveRepeated === true) {
47
- const values = new Map;
48
- for (const [key, value] of formData.entries()) {
49
- const entries = values.get(key);
50
- if (entries)
51
- entries.push(value);
52
- else
53
- values.set(key, [value]);
54
- }
55
- return Object.fromEntries(values);
56
- }
57
- const values = {};
58
- for (const [key, value] of formData.entries()) {
59
- if (typeof value === "string") {
60
- values[key] = value;
61
- }
62
- }
63
- return values;
64
- }
2
+ // ../../src/core/http/formRequest.ts
3
+ import { ForbiddenError } from "@getstrata/core/errors/http";
65
4
 
66
5
  // ../../src/core/http/validation.ts
67
6
  import { currentAuthUser } from "@getstrata/core/auth/authContext";
68
- import { BadRequestError as BadRequestError2 } from "@getstrata/core/errors/http";
7
+ import { BadRequestError } from "@getstrata/core/errors/http";
69
8
  import { currentTenant } from "@getstrata/core/tenant/tenantContext";
70
9
  function buildRequestCacheKey(fallbackPath, request) {
71
10
  if (!request) {
@@ -88,9 +27,9 @@ function parseOptionalPositiveIntQueryParam(params, name) {
88
27
  if (value === null || value.trim() === "") {
89
28
  return;
90
29
  }
91
- const parsed = Number.parseInt(value, 10);
92
- if (!Number.isInteger(parsed) || parsed <= 0) {
93
- throw new BadRequestError2(`Invalid query parameter "${name}". Expected a positive integer.`);
30
+ const parsed = Number(value);
31
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
32
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a positive integer.`);
94
33
  }
95
34
  return parsed;
96
35
  }
@@ -107,7 +46,7 @@ function parseOptionalBooleanQueryParam(params, name) {
107
46
  case "0":
108
47
  return false;
109
48
  default:
110
- throw new BadRequestError2(`Invalid query parameter "${name}". Expected a boolean.`);
49
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected a boolean.`);
111
50
  }
112
51
  }
113
52
  function parseOptionalEnumQueryParam(params, name, allowedValues) {
@@ -116,13 +55,13 @@ function parseOptionalEnumQueryParam(params, name, allowedValues) {
116
55
  return;
117
56
  }
118
57
  if (!allowedValues.includes(value)) {
119
- throw new BadRequestError2(`Invalid query parameter "${name}". Expected one of: ${allowedValues.join(", ")}.`);
58
+ throw new BadRequestError(`Invalid query parameter "${name}". Expected one of: ${allowedValues.join(", ")}.`);
120
59
  }
121
60
  return value;
122
61
  }
123
62
  function expectObject(value, label = "request body") {
124
63
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
125
- throw new BadRequestError2(`${label} must be a JSON object.`);
64
+ throw new BadRequestError(`${label} must be a JSON object.`);
126
65
  }
127
66
  return value;
128
67
  }
@@ -131,24 +70,24 @@ async function parseJsonBody(request, validator) {
131
70
  try {
132
71
  payload = await request.json();
133
72
  } catch {
134
- throw new BadRequestError2("Request body must be valid JSON.");
73
+ throw new BadRequestError("Request body must be valid JSON.");
135
74
  }
136
75
  return validator(payload);
137
76
  }
138
77
  function readRequiredString(payload, field, options = {}) {
139
78
  const value = payload[field];
140
79
  if (typeof value !== "string" || value.trim() === "") {
141
- throw new BadRequestError2(`"${field}" is required and must be a string.`);
80
+ throw new BadRequestError(`"${field}" is required and must be a string.`);
142
81
  }
143
82
  const trimmed = value.trim();
144
83
  if (options.minLength !== undefined && trimmed.length < options.minLength) {
145
- throw new BadRequestError2(`"${field}" must be at least ${options.minLength} characters.`);
84
+ throw new BadRequestError(`"${field}" must be at least ${options.minLength} characters.`);
146
85
  }
147
86
  if (options.maxLength !== undefined && trimmed.length > options.maxLength) {
148
- throw new BadRequestError2(`"${field}" must be at most ${options.maxLength} characters.`);
87
+ throw new BadRequestError(`"${field}" must be at most ${options.maxLength} characters.`);
149
88
  }
150
89
  if (options.pattern && !options.pattern.test(trimmed)) {
151
- throw new BadRequestError2(`"${field}" has an invalid format.`);
90
+ throw new BadRequestError(`"${field}" has an invalid format.`);
152
91
  }
153
92
  return trimmed;
154
93
  }
@@ -161,7 +100,7 @@ function readOptionalString(payload, field, options = {}) {
161
100
  function readRequiredEnum(payload, field, allowedValues) {
162
101
  const value = readRequiredString(payload, field);
163
102
  if (!allowedValues.includes(value)) {
164
- throw new BadRequestError2(`"${field}" must be one of: ${allowedValues.join(", ")}.`);
103
+ throw new BadRequestError(`"${field}" must be one of: ${allowedValues.join(", ")}.`);
165
104
  }
166
105
  return value;
167
106
  }
@@ -174,7 +113,7 @@ function readOptionalEnum(payload, field, allowedValues) {
174
113
  function readRequiredPositiveInt(payload, field) {
175
114
  const value = payload[field];
176
115
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
177
- throw new BadRequestError2(`"${field}" is required and must be a positive integer.`);
116
+ throw new BadRequestError(`"${field}" is required and must be a positive integer.`);
178
117
  }
179
118
  return value;
180
119
  }
@@ -185,38 +124,78 @@ function readOptionalPositiveInt(payload, field) {
185
124
  return readRequiredPositiveInt(payload, field);
186
125
  }
187
126
  function parsePositiveIntParam(value, name = "id") {
188
- const parsed = Number.parseInt(value, 10);
189
- if (!Number.isInteger(parsed) || parsed <= 0) {
190
- throw new BadRequestError2(`Invalid ${name}. Expected a positive integer.`);
127
+ const parsed = Number(value);
128
+ if (!/^[0-9]+$/.test(value.trim()) || !Number.isSafeInteger(parsed) || parsed <= 0) {
129
+ throw new BadRequestError(`Invalid ${name}. Expected a positive integer.`);
191
130
  }
192
131
  return parsed;
193
132
  }
194
133
 
195
- // ../../src/core/http/webFormRequest.ts
196
- class WebFormRequest {
197
- #preserveRepeated;
198
- constructor(options = {}) {
199
- this.#preserveRepeated = options.preserveRepeated === true;
200
- }
134
+ // ../../src/core/http/formRequest.ts
135
+ class FormRequest {
201
136
  authorize(_request) {
202
137
  return true;
203
138
  }
204
139
  validatePayload(payload) {
205
140
  return this.parse(payload);
206
141
  }
142
+ readPayload(request) {
143
+ return parseJsonBody(request, (payload) => payload);
144
+ }
207
145
  async validate(request) {
208
- if (!await this.authorize(request)) {
146
+ if (await this.authorize(request) !== true) {
209
147
  throw new ForbiddenError;
210
148
  }
211
- const payload = requestPrefersJson(request) ? await parseJsonBody(request, (body) => body) : await parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
212
- try {
213
- return this.validatePayload(payload);
214
- } catch (error) {
215
- if (error instanceof ValidationError) {
216
- throw error;
217
- }
218
- throw error;
149
+ return this.validatePayload(await this.readPayload(request));
150
+ }
151
+ }
152
+
153
+ class QueryFormRequest {
154
+ validate(request) {
155
+ return this.parseQuery(request);
156
+ }
157
+ }
158
+
159
+ // ../../src/core/http/parseFormBody.ts
160
+ import { BadRequestError as BadRequestError2 } from "@getstrata/core/errors/http";
161
+ async function parseFormBody(request, options = {}) {
162
+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
163
+ if (!contentType.includes("application/x-www-form-urlencoded") && !contentType.includes("multipart/form-data")) {
164
+ throw new BadRequestError2("Expected a form submission.");
165
+ }
166
+ return formDataToRecord(await request.formData(), options);
167
+ }
168
+ function formDataToRecord(formData, options = {}) {
169
+ if (options.preserveRepeated === true) {
170
+ const values = new Map;
171
+ for (const [key, value] of formData.entries()) {
172
+ const entries = values.get(key);
173
+ if (entries)
174
+ entries.push(value);
175
+ else
176
+ values.set(key, [value]);
219
177
  }
178
+ return Object.fromEntries(values);
179
+ }
180
+ const values = {};
181
+ for (const [key, value] of formData.entries()) {
182
+ if (typeof value === "string") {
183
+ values[key] = value;
184
+ }
185
+ }
186
+ return values;
187
+ }
188
+
189
+ // ../../src/core/http/webFormRequest.ts
190
+ class WebFormRequest extends FormRequest {
191
+ #preserveRepeated;
192
+ constructor(options = {}) {
193
+ super();
194
+ this.#preserveRepeated = options.preserveRepeated === true;
195
+ }
196
+ readPayload(request) {
197
+ const mediaType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
198
+ return mediaType === "application/json" || mediaType?.match(/^application\/[^/]+\+json$/) ? parseJsonBody(request, (body) => body) : parseFormBody(request, { preserveRepeated: this.#preserveRepeated });
220
199
  }
221
200
  }
222
201
  export {
@@ -59,6 +59,14 @@ class AsyncQueue {
59
59
  if (this.closed)
60
60
  throw new Error("Async queue is closed.");
61
61
  }
62
+ track(running) {
63
+ const settled = running.then(() => {}, () => {});
64
+ this.active.add(settled);
65
+ settled.then(() => {
66
+ this.active.delete(settled);
67
+ });
68
+ return running;
69
+ }
62
70
  enqueue(task, onError) {
63
71
  this.assertOpen();
64
72
  const running = new Promise((resolve) => {
@@ -66,10 +74,7 @@ class AsyncQueue {
66
74
  Promise.resolve().then(task).catch(onError).finally(resolve);
67
75
  }, 0);
68
76
  });
69
- this.active.add(running);
70
- running.then(() => {
71
- this.active.delete(running);
72
- });
77
+ this.track(running);
73
78
  }
74
79
  async dispatch(job, payload, options) {
75
80
  if (options?.handoff !== undefined)
@@ -23,6 +23,14 @@ class AsyncQueue {
23
23
  if (this.closed)
24
24
  throw new Error("Async queue is closed.");
25
25
  }
26
+ track(running) {
27
+ const settled = running.then(() => {}, () => {});
28
+ this.active.add(settled);
29
+ settled.then(() => {
30
+ this.active.delete(settled);
31
+ });
32
+ return running;
33
+ }
26
34
  enqueue(task, onError) {
27
35
  this.assertOpen();
28
36
  const running = new Promise((resolve) => {
@@ -30,10 +38,7 @@ class AsyncQueue {
30
38
  Promise.resolve().then(task).catch(onError).finally(resolve);
31
39
  }, 0);
32
40
  });
33
- this.active.add(running);
34
- running.then(() => {
35
- this.active.delete(running);
36
- });
41
+ this.track(running);
37
42
  }
38
43
  async dispatch(job, payload, options) {
39
44
  if (options?.handoff !== undefined)
@@ -1534,6 +1534,14 @@ class AsyncQueue {
1534
1534
  if (this.closed)
1535
1535
  throw new Error("Async queue is closed.");
1536
1536
  }
1537
+ track(running) {
1538
+ const settled = running.then(() => {}, () => {});
1539
+ this.active.add(settled);
1540
+ settled.then(() => {
1541
+ this.active.delete(settled);
1542
+ });
1543
+ return running;
1544
+ }
1537
1545
  enqueue(task, onError) {
1538
1546
  this.assertOpen();
1539
1547
  const running = new Promise((resolve) => {
@@ -1541,10 +1549,7 @@ class AsyncQueue {
1541
1549
  Promise.resolve().then(task).catch(onError).finally(resolve);
1542
1550
  }, 0);
1543
1551
  });
1544
- this.active.add(running);
1545
- running.then(() => {
1546
- this.active.delete(running);
1547
- });
1552
+ this.track(running);
1548
1553
  }
1549
1554
  async dispatch(job, payload, options) {
1550
1555
  if (options?.handoff !== undefined)
@@ -1606,7 +1611,7 @@ class ResilientQueue extends AsyncQueue {
1606
1611
  });
1607
1612
  return;
1608
1613
  }
1609
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1614
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1610
1615
  }
1611
1616
  }
1612
1617
 
@@ -1531,6 +1531,14 @@ class AsyncQueue {
1531
1531
  if (this.closed)
1532
1532
  throw new Error("Async queue is closed.");
1533
1533
  }
1534
+ track(running) {
1535
+ const settled = running.then(() => {}, () => {});
1536
+ this.active.add(settled);
1537
+ settled.then(() => {
1538
+ this.active.delete(settled);
1539
+ });
1540
+ return running;
1541
+ }
1534
1542
  enqueue(task, onError) {
1535
1543
  this.assertOpen();
1536
1544
  const running = new Promise((resolve) => {
@@ -1538,10 +1546,7 @@ class AsyncQueue {
1538
1546
  Promise.resolve().then(task).catch(onError).finally(resolve);
1539
1547
  }, 0);
1540
1548
  });
1541
- this.active.add(running);
1542
- running.then(() => {
1543
- this.active.delete(running);
1544
- });
1549
+ this.track(running);
1545
1550
  }
1546
1551
  async dispatch(job, payload, options) {
1547
1552
  if (options?.handoff !== undefined)
@@ -1603,7 +1608,7 @@ class ResilientQueue extends AsyncQueue {
1603
1608
  });
1604
1609
  return;
1605
1610
  }
1606
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1611
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1607
1612
  }
1608
1613
  }
1609
1614
 
@@ -1531,6 +1531,14 @@ class AsyncQueue {
1531
1531
  if (this.closed)
1532
1532
  throw new Error("Async queue is closed.");
1533
1533
  }
1534
+ track(running) {
1535
+ const settled = running.then(() => {}, () => {});
1536
+ this.active.add(settled);
1537
+ settled.then(() => {
1538
+ this.active.delete(settled);
1539
+ });
1540
+ return running;
1541
+ }
1534
1542
  enqueue(task, onError) {
1535
1543
  this.assertOpen();
1536
1544
  const running = new Promise((resolve) => {
@@ -1538,10 +1546,7 @@ class AsyncQueue {
1538
1546
  Promise.resolve().then(task).catch(onError).finally(resolve);
1539
1547
  }, 0);
1540
1548
  });
1541
- this.active.add(running);
1542
- running.then(() => {
1543
- this.active.delete(running);
1544
- });
1549
+ this.track(running);
1545
1550
  }
1546
1551
  async dispatch(job, payload, options) {
1547
1552
  if (options?.handoff !== undefined)
@@ -1603,7 +1608,7 @@ class ResilientQueue extends AsyncQueue {
1603
1608
  });
1604
1609
  return;
1605
1610
  }
1606
- await runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy });
1611
+ await this.track(Promise.resolve().then(() => runQueueJob(envelope, this.failedJobs, this.registry, { retryPolicy: this.retryPolicy })));
1607
1612
  }
1608
1613
  }
1609
1614
 
@@ -23,6 +23,14 @@ class AsyncQueue {
23
23
  if (this.closed)
24
24
  throw new Error("Async queue is closed.");
25
25
  }
26
+ track(running) {
27
+ const settled = running.then(() => {}, () => {});
28
+ this.active.add(settled);
29
+ settled.then(() => {
30
+ this.active.delete(settled);
31
+ });
32
+ return running;
33
+ }
26
34
  enqueue(task, onError) {
27
35
  this.assertOpen();
28
36
  const running = new Promise((resolve) => {
@@ -30,10 +38,7 @@ class AsyncQueue {
30
38
  Promise.resolve().then(task).catch(onError).finally(resolve);
31
39
  }, 0);
32
40
  });
33
- this.active.add(running);
34
- running.then(() => {
35
- this.active.delete(running);
36
- });
41
+ this.track(running);
37
42
  }
38
43
  async dispatch(job, payload, options) {
39
44
  if (options?.handoff !== undefined)
@@ -959,6 +959,32 @@ import {
959
959
  service as service2,
960
960
  valueService as valueService2
961
961
  } from "@getstrata/core/contracts/services";
962
+
963
+ // ../../src/core/contracts/provider.ts
964
+ function defineProvider(options) {
965
+ const { name, requires, services, setup, boot } = options;
966
+ if (typeof name !== "string" || name.trim().length === 0) {
967
+ throw new TypeError("Provider names must be nonempty strings.");
968
+ }
969
+ if (requires !== undefined && (!Array.isArray(requires) || requires.some((name) => typeof name !== "string" || name.trim().length === 0))) {
970
+ throw new TypeError("Provider dependencies must be an array of nonempty names.");
971
+ }
972
+ if (services !== undefined && !Array.isArray(services)) {
973
+ throw new TypeError("Provider services must be an array.");
974
+ }
975
+ if (setup !== undefined && typeof setup !== "function" || boot !== undefined && typeof boot !== "function") {
976
+ throw new TypeError("Provider hooks must be functions.");
977
+ }
978
+ return Object.freeze({
979
+ name,
980
+ requires: Object.freeze([...requires ?? []]),
981
+ services: Object.freeze([...services ?? []]),
982
+ setup: setup ?? (() => {}),
983
+ ...boot ? { boot } : {}
984
+ });
985
+ }
986
+
987
+ // ../../src/core/runtime/application.ts
962
988
  function deferred() {
963
989
  let resolve;
964
990
  let reject;
@@ -1045,6 +1071,12 @@ function normalize(input) {
1045
1071
  if (item.requires !== undefined && !Array.isArray(item.requires)) {
1046
1072
  throw new TypeError("Provider dependencies must be an array.");
1047
1073
  }
1074
+ if (item.services !== undefined && !Array.isArray(item.services)) {
1075
+ throw new TypeError("Provider services must be an array.");
1076
+ }
1077
+ if (item.boot !== undefined && typeof item.boot !== "function") {
1078
+ throw new TypeError("Provider boot must be a function.");
1079
+ }
1048
1080
  const requires = [...item.requires ?? []];
1049
1081
  for (const dependency of requires)
1050
1082
  declarationName2(dependency);
@@ -1052,6 +1084,8 @@ function normalize(input) {
1052
1084
  return Object.freeze({
1053
1085
  name: item.name,
1054
1086
  setup: item.setup,
1087
+ ...item.boot ? { boot: item.boot } : {},
1088
+ services: Object.freeze([...item.services ?? []]),
1055
1089
  requires: Object.freeze(requires)
1056
1090
  });
1057
1091
  });
@@ -1090,7 +1124,11 @@ function normalize(input) {
1090
1124
  transports: orderedTransports,
1091
1125
  shutdownTimeoutMs: timeout(input.shutdownTimeoutMs),
1092
1126
  startupCleanupTimeoutMs: timeout(input.startupCleanupTimeoutMs),
1093
- services: compileServiceGraph(input.services, input.overrides)
1127
+ services: compileServiceGraph([
1128
+ ...input.services ?? [],
1129
+ ...providers.flatMap((item) => item.services ?? []),
1130
+ ...transports.flatMap((item) => item.services ?? [])
1131
+ ], input.overrides)
1094
1132
  };
1095
1133
  }
1096
1134
 
@@ -1431,7 +1469,15 @@ class OwnedApplication {
1431
1469
  await this.definition.services.start(this.services, this.cancellation.signal, {
1432
1470
  acquire: (group, spec, signal, validate) => this.journal.acquire(group, spec, signal, validate)
1433
1471
  });
1434
- for (const provider of [...this.definition.providers, ...this.definition.transports]) {
1472
+ const hooks = [
1473
+ ...this.definition.providers.map((provider) => ({ provider, hook: provider.setup })),
1474
+ ...this.definition.providers.flatMap((provider) => provider.boot ? [{ provider, hook: provider.boot }] : []),
1475
+ ...this.definition.transports.flatMap((provider) => [
1476
+ { provider, hook: provider.setup },
1477
+ ...provider.boot ? [{ provider, hook: provider.boot }] : []
1478
+ ])
1479
+ ];
1480
+ for (const { provider, hook } of hooks) {
1435
1481
  if (this.cancellation.signal.aborted)
1436
1482
  throw this.cancelled;
1437
1483
  let active = true;
@@ -1454,7 +1500,7 @@ class OwnedApplication {
1454
1500
  return result;
1455
1501
  }
1456
1502
  });
1457
- const operation = leasedOperation(() => provider.setup(scope), () => {
1503
+ const operation = leasedOperation(() => hook(scope), () => {
1458
1504
  active = false;
1459
1505
  });
1460
1506
  operation.invoke();
@@ -1579,6 +1625,7 @@ export {
1579
1625
  CORE_EXECUTION_CONTEXT_TOKEN2 as CORE_EXECUTION_CONTEXT_TOKEN,
1580
1626
  aliasService2 as aliasService,
1581
1627
  createApplication,
1628
+ defineProvider,
1582
1629
  resourceService2 as resourceService,
1583
1630
  service2 as service,
1584
1631
  valueService2 as valueService
@@ -2,6 +2,38 @@
2
2
  // ../../src/core/security/oauthState.ts
3
3
  import { createHmac, randomBytes, timingSafeEqual } from "crypto";
4
4
 
5
+ // ../../src/core/http/cookies.ts
6
+ function readRequestCookie(request, name) {
7
+ const cookies = request.cookies;
8
+ if (cookies && typeof cookies.get === "function") {
9
+ const value = cookies.get(name);
10
+ if (value) {
11
+ return value;
12
+ }
13
+ }
14
+ const header = request.headers.get("cookie");
15
+ if (!header) {
16
+ return null;
17
+ }
18
+ for (const part of header.split(";")) {
19
+ const idx = part.indexOf("=");
20
+ if (idx === -1)
21
+ continue;
22
+ const cookieName = part.slice(0, idx).trim();
23
+ if (cookieName !== name)
24
+ continue;
25
+ try {
26
+ return decodeURIComponent(part.slice(idx + 1).trim());
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ function readBunRequestCookie(request, name) {
34
+ return request.cookies.get(name) ?? readRequestCookie(request, name);
35
+ }
36
+
5
37
  // ../../src/core/runtime/appEnv.ts
6
38
  var NON_PRODUCTION_APP_ENVS = new Set(["local", "development", "dev", "test", "testing", "ci"]);
7
39
  function normalizeEnvValue(value) {
@@ -58,6 +90,7 @@ function otelServiceName(env = process.env) {
58
90
 
59
91
  // ../../src/core/security/oauthState.ts
60
92
  var OAUTH_STATE_COOKIE = "oauth_state";
93
+ var SAML_STATE_COOKIE = "saml_state";
61
94
  var OIDC_PKCE_COOKIE = "oidc_pkce";
62
95
  var OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
63
96
  function resolveOAuthStateSecret() {
@@ -104,11 +137,33 @@ function createOAuthStateCookie(options) {
104
137
  cookie: `${OAUTH_STATE_COOKIE}=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600${options?.production ?? isProductionEnv() ? "; Secure" : ""}`
105
138
  };
106
139
  }
107
- function verifyOAuthState(_request, returnedState, options) {
140
+ function verifyOAuthState(request, returnedState, options) {
141
+ return verifyBrowserState(request, returnedState, OAUTH_STATE_COOKIE, options);
142
+ }
143
+ function verifyBrowserState(request, returnedState, cookieName, options) {
108
144
  if (!returnedState || returnedState.trim().length === 0) {
109
145
  return false;
110
146
  }
111
- return verifySignedOAuthStateValue(returnedState.trim(), options);
147
+ const state = returnedState.trim();
148
+ const cookie = readRequestCookie(request, cookieName);
149
+ if (!cookie)
150
+ return false;
151
+ const expected = Buffer.from(cookie);
152
+ const actual = Buffer.from(state);
153
+ return expected.length === actual.length && timingSafeEqual(expected, actual) && verifySignedOAuthStateValue(state, options);
154
+ }
155
+ function createSamlStateCookie(options) {
156
+ const { state } = createOAuthState(options);
157
+ return {
158
+ state,
159
+ cookie: `${SAML_STATE_COOKIE}=${encodeURIComponent(state)}; Path=/; HttpOnly; SameSite=None; Max-Age=600; Secure`
160
+ };
161
+ }
162
+ function verifySamlState(request, returnedState, options) {
163
+ return verifyBrowserState(request, returnedState, SAML_STATE_COOKIE, options);
164
+ }
165
+ function clearSamlStateCookie() {
166
+ return `${SAML_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=None; Max-Age=0; Secure`;
112
167
  }
113
168
  function clearOAuthStateCookie(options) {
114
169
  return `${OAUTH_STATE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${options?.production ?? isProductionEnv() ? "; Secure" : ""}`;
@@ -186,12 +241,16 @@ function unsealOidcPkceValue(rawValue, returnedState, options) {
186
241
  export {
187
242
  OAUTH_STATE_COOKIE,
188
243
  OIDC_PKCE_COOKIE,
244
+ SAML_STATE_COOKIE,
189
245
  clearOAuthStateCookie,
190
246
  clearOidcPkceCookie,
247
+ clearSamlStateCookie,
191
248
  createOAuthState,
192
249
  createOAuthStateCookie,
250
+ createSamlStateCookie,
193
251
  readOidcPkceCookie,
194
252
  sealOidcPkceCookie,
195
253
  verifyOAuthState,
254
+ verifySamlState,
196
255
  verifySignedOAuthStateValue
197
256
  };