@getstrata/core 2.2.59 → 3.0.3
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.
- package/CHANGELOG.md +27 -0
- package/dist/core/audit/exportAuditLogs.d.ts +12 -3
- package/dist/core/audit/exportStore.d.ts +6 -2
- package/dist/core/audit/siemFormatter.d.ts +2 -2
- package/dist/core/auth/abilityCatalog.d.ts +1 -9
- package/dist/core/auth/authContext.d.ts +2 -0
- package/dist/core/auth/authOutcome.d.ts +32 -0
- package/dist/core/auth/authReader.d.ts +22 -0
- package/dist/core/auth/basicAuthGuard.d.ts +19 -3
- package/dist/core/auth/emailVerification.d.ts +1 -1
- package/dist/core/auth/guard.d.ts +27 -6
- package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
- package/dist/core/auth/jwt.d.ts +5 -4
- package/dist/core/auth/jwtGuard.d.ts +7 -6
- package/dist/core/auth/membershipContext.d.ts +10 -7
- package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
- package/dist/core/auth/membershipMiddleware.d.ts +1 -2
- package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
- package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
- package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
- package/dist/core/auth/oauth/providers.d.ts +3 -1
- package/dist/core/auth/oneTimeToken.d.ts +2 -3
- package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
- package/dist/core/auth/passwordLogin.d.ts +5 -5
- package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
- package/dist/core/auth/policy.d.ts +23 -10
- package/dist/core/auth/requireAuthCapability.d.ts +3 -0
- package/dist/core/auth/resolveMembershipService.d.ts +3 -2
- package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
- package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
- package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
- package/dist/core/auth/sessionCookie.d.ts +20 -9
- package/dist/core/auth/sessionGuard.d.ts +14 -3
- package/dist/core/cache/createCacheStore.d.ts +6 -3
- package/dist/core/cache/redisCacheStore.d.ts +5 -1
- package/dist/core/cache/repository.d.ts +5 -1
- package/dist/core/cache/simpleCache.d.ts +2 -1
- package/dist/core/cache/tokens.d.ts +8 -0
- package/dist/core/config/applicationConfig.d.ts +21 -0
- package/dist/core/config/configSnapshot.d.ts +3 -0
- package/dist/core/config/envSchema.d.ts +3 -2
- package/dist/core/contracts/application.d.ts +153 -0
- package/dist/core/contracts/authUserDirectory.d.ts +24 -7
- package/dist/core/contracts/container.d.ts +20 -23
- package/dist/core/contracts/di.d.ts +4 -2
- package/dist/core/contracts/executionContext.d.ts +5 -0
- package/dist/core/contracts/executionOperations.d.ts +10 -0
- package/dist/core/contracts/executionOwnership.d.ts +38 -0
- package/dist/core/contracts/persistence.d.ts +20 -0
- package/dist/core/contracts/serviceTokens.d.ts +32 -18
- package/dist/core/contracts/services.d.ts +63 -0
- package/dist/core/contracts/token.d.ts +19 -0
- package/dist/core/crypto/fieldEncryption.d.ts +19 -7
- package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
- package/dist/core/crypto/mfaSecret.d.ts +10 -3
- package/dist/core/database/baseRepository.d.ts +14 -10
- package/dist/core/database/bindings.d.ts +6 -0
- package/dist/core/database/bunSql.d.ts +3 -12
- package/dist/core/database/definitions.d.ts +209 -0
- package/dist/core/database/dialect.d.ts +5 -24
- package/dist/core/database/driverPorts.d.ts +116 -0
- package/dist/core/database/errors.d.ts +47 -7
- package/dist/core/database/factory.d.ts +51 -31
- package/dist/core/database/index.d.ts +9 -10
- package/dist/core/database/keyset.d.ts +2 -1
- package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
- package/dist/core/database/manager.d.ts +12 -0
- package/dist/core/database/model.d.ts +91 -97
- package/dist/core/database/modelQuery.d.ts +9 -5
- package/dist/core/database/modelRegistry.d.ts +52 -33
- package/dist/core/database/mysqlConnection.d.ts +1 -19
- package/dist/core/database/mysqlNative.d.ts +38 -0
- package/dist/core/database/nativeTransactions.d.ts +16 -0
- package/dist/core/database/ormInternal.d.ts +85 -0
- package/dist/core/database/ormRuntime.d.ts +4 -0
- package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
- package/dist/core/database/postgresNative.d.ts +11 -0
- package/dist/core/database/query.d.ts +24 -23
- package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
- package/dist/core/database/rawMysql.d.ts +7 -0
- package/dist/core/database/rawPostgres.d.ts +23 -0
- package/dist/core/database/rawSqlite.d.ts +6 -0
- package/dist/core/database/relationQueries.d.ts +3 -2
- package/dist/core/database/relationQuery.d.ts +24 -6
- package/dist/core/database/repositoryQuery.d.ts +6 -1
- package/dist/core/database/schema/driver.d.ts +1 -1
- package/dist/core/database/seeders/types.d.ts +1 -1
- package/dist/core/database/session.d.ts +13 -0
- package/dist/core/database/sessionFactory.d.ts +9 -0
- package/dist/core/database/sqlDialects.d.ts +22 -0
- package/dist/core/database/tokens.d.ts +7 -0
- package/dist/core/database/transactionSession.d.ts +43 -0
- package/dist/core/errors/http.d.ts +4 -1
- package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
- package/dist/core/events/index.d.ts +2 -3
- package/dist/core/events/outbox/index.d.ts +44 -13
- package/dist/core/events/outbox/metrics.d.ts +4 -4
- package/dist/core/events/outbox/workerTransport.d.ts +17 -0
- package/dist/core/http/authMiddleware.d.ts +2 -2
- package/dist/core/http/authorizeMiddleware.d.ts +2 -2
- package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
- package/dist/core/http/conditionalResponse.d.ts +7 -2
- package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
- package/dist/core/http/corsMiddleware.d.ts +2 -1
- package/dist/core/http/csrfMiddleware.d.ts +6 -1
- package/dist/core/http/csrfToken.d.ts +17 -7
- package/dist/core/http/databaseError.d.ts +4 -0
- package/dist/core/http/etag.d.ts +5 -2
- package/dist/core/http/flashMiddleware.d.ts +1 -1
- package/dist/core/http/flashSession.d.ts +13 -7
- package/dist/core/http/index.d.ts +1 -1
- package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
- package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
- package/dist/core/http/parseMultipartUpload.d.ts +3 -2
- package/dist/core/http/requestMetaContext.d.ts +5 -0
- package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
- package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
- package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
- package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
- package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
- package/dist/core/http/response.d.ts +4 -3
- package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
- package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
- package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
- package/dist/core/http/signedUrl.d.ts +8 -6
- package/dist/core/http/throttleMiddleware.d.ts +9 -5
- package/dist/core/http/uploads.d.ts +9 -3
- package/dist/core/http/webErrorResponse.d.ts +8 -2
- package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
- package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
- package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
- package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
- package/dist/core/mail/mailer.d.ts +7 -5
- package/dist/core/openapi/generator.d.ts +12 -4
- package/dist/core/openapi/registeredRoute.d.ts +4 -4
- package/dist/core/queue/createAppQueue.d.ts +9 -4
- package/dist/core/queue/failedJobMetrics.d.ts +11 -2
- package/dist/core/queue/failedJobRepository.d.ts +6 -3
- package/dist/core/queue/failedJobService.d.ts +1 -0
- package/dist/core/queue/index.d.ts +16 -6
- package/dist/core/queue/jobRegistry.d.ts +3 -2
- package/dist/core/queue/jobRunner.d.ts +10 -4
- package/dist/core/queue/publicQueue.d.ts +18 -9
- package/dist/core/queue/queueConfig.d.ts +20 -10
- package/dist/core/queue/queueHandoff.d.ts +31 -0
- package/dist/core/queue/queueMetrics.d.ts +10 -3
- package/dist/core/queue/queueServices.d.ts +28 -0
- package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
- package/dist/core/queue/redisQueue.d.ts +19 -10
- package/dist/core/queue/redisQueueKeys.d.ts +5 -5
- package/dist/core/queue/redisStreams.d.ts +17 -10
- package/dist/core/queue/resilientQueue.d.ts +10 -4
- package/dist/core/queue/types.d.ts +1 -0
- package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
- package/dist/core/runtime/application.d.ts +7 -0
- package/dist/core/runtime/executionContext.d.ts +9 -0
- package/dist/core/runtime/executionTasks.d.ts +49 -0
- package/dist/core/runtime/resourceJournal.d.ts +67 -0
- package/dist/core/runtime/serviceGraph.d.ts +14 -0
- package/dist/core/security/oauthState.d.ts +13 -9
- package/dist/core/security/publicReads.d.ts +2 -2
- package/dist/core/security/safeFetch.d.ts +1 -0
- package/dist/core/security/safeUrl.d.ts +3 -0
- package/dist/core/security/scimTenantTokens.d.ts +1 -1
- package/dist/core/security/tokenExpiry.d.ts +1 -1
- package/dist/core/security/webhookSignature.d.ts +1 -1
- package/dist/core/storage/storage.d.ts +24 -16
- package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
- package/dist/core/tenant/resolveTenant.d.ts +2 -2
- package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
- package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
- package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
- package/dist/core/tracing/otel.d.ts +4 -6
- package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
- package/dist/core/view/etaViewEngine.d.ts +1 -1
- package/dist/core/view/index.d.ts +5 -4
- package/dist/core/view/tokens.d.ts +8 -0
- package/dist/core/view/viewRenderer.d.ts +2 -2
- package/dist/core/view/webErrorView.d.ts +8 -7
- package/dist/core/view/webLayoutData.d.ts +6 -4
- package/dist/entries/audit/exportAuditLogs.js +87 -1024
- package/dist/entries/audit/siemFormatter.js +4 -90
- package/dist/entries/auth/abilityCatalog.js +28 -0
- package/dist/entries/auth/accessControl.js +5 -16
- package/dist/entries/auth/accountStateMigration.js +216 -236
- package/dist/entries/auth/authOutcome.js +80 -0
- package/dist/entries/auth/authReader.js +68 -0
- package/dist/entries/auth/basicAuthGuard.js +144 -1249
- package/dist/entries/auth/emailVerification.js +2 -2
- package/dist/entries/auth/intendedUrlCookie.js +35 -59
- package/dist/entries/auth/jwt.js +22 -47
- package/dist/entries/auth/jwtGuard.js +99 -231
- package/dist/entries/auth/membershipMiddleware.js +71 -10
- package/dist/entries/auth/membershipScope.js +16 -22
- package/dist/entries/auth/membershipService.js +11 -28
- package/dist/entries/auth/oauth/oidcProvider.js +59 -64
- package/dist/entries/auth/oauth/providers.js +12 -95
- package/dist/entries/auth/oauth/samlProvider.js +53 -1080
- package/dist/entries/auth/oneTimeToken.js +27 -289
- package/dist/entries/auth/passwordConfirmCookie.js +40 -63
- package/dist/entries/auth/passwordLogin.js +94 -399
- package/dist/entries/auth/pendingMfaCookie.js +6 -6
- package/dist/entries/auth/policy.js +22 -56
- package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
- package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
- package/dist/entries/auth/sessionCookie.js +58 -73
- package/dist/entries/auth/sessionGuard.js +95 -248
- package/dist/entries/auth/tokenHash.js +11 -43
- package/dist/entries/cache/createCacheStore.js +126 -117
- package/dist/entries/cache/repository.js +25 -0
- package/dist/entries/cache/simpleCache.js +12 -7
- package/dist/entries/cache/tokens.js +9 -0
- package/dist/entries/config/applicationConfig.js +163 -0
- package/dist/entries/config/envSchema.js +21 -4
- package/dist/entries/contracts/application.js +1 -0
- package/dist/entries/contracts/authUserDirectory.js +10 -0
- package/dist/entries/contracts/container.js +99 -26
- package/dist/entries/contracts/di.js +3 -0
- package/dist/entries/contracts/executionContext.js +7 -0
- package/dist/entries/contracts/executionOperations.js +7 -0
- package/dist/entries/contracts/executionOwnership.js +7 -0
- package/dist/entries/contracts/membership.js +1 -0
- package/dist/entries/contracts/persistence.js +1 -0
- package/dist/entries/contracts/serviceTokens.js +26 -116
- package/dist/entries/contracts/services.js +98 -0
- package/dist/entries/contracts/token.js +41 -0
- package/dist/entries/crypto/fieldEncryption.js +49 -50
- package/dist/entries/crypto/mfaSecret.js +86 -82
- package/dist/entries/database/acquisitionMetrics.js +107 -0
- package/dist/entries/database/baseRepository.d.ts +2 -0
- package/dist/entries/database/bindings.js +2082 -0
- package/dist/entries/database/definitions.js +175 -0
- package/dist/entries/database/errors.js +114 -89
- package/dist/entries/database/factory.js +67 -28
- package/dist/entries/database/migrations.js +172 -224
- package/dist/entries/database/model.d.ts +1 -0
- package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
- package/dist/entries/database/query.js +159 -161
- package/dist/entries/database/repositoryQuery.d.ts +1 -0
- package/dist/entries/database/repositoryQuery.js +1 -1373
- package/dist/entries/database/schema.js +216 -236
- package/dist/entries/database/session.js +1 -0
- package/dist/entries/database/sqliteConnection.js +525 -83
- package/dist/entries/database/tokens.js +9 -0
- package/dist/entries/errors/http.js +118 -1
- package/dist/entries/http/authMiddleware.js +8 -5
- package/dist/entries/http/authorizeMiddleware.js +1 -1
- package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
- package/dist/entries/http/clientIp.js +2 -2
- package/dist/entries/http/conditionalResponse.js +19 -7
- package/dist/entries/http/corsMiddleware.js +6 -101
- package/dist/entries/http/csrfMiddleware.js +92 -106
- package/dist/entries/http/csrfToken.js +58 -94
- package/dist/entries/http/etag.js +7 -4
- package/dist/entries/http/flashMiddleware.js +57 -99
- package/dist/entries/http/flashSession.js +41 -68
- package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
- package/dist/entries/http/metricsMiddleware.js +2 -16
- package/dist/entries/http/parseMultipartUpload.js +15 -29
- package/dist/entries/http/requireAbilityMiddleware.js +2 -2
- package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
- package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
- package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
- package/dist/entries/http/response.js +67 -233
- package/dist/entries/http/routeMiddleware.js +0 -14
- package/dist/entries/http/scimThrottleMiddleware.js +43 -237
- package/dist/entries/http/securedRouteModelBinding.js +37 -25
- package/dist/entries/http/securityHeadersMiddleware.js +8 -25
- package/dist/entries/http/signedUrl.js +20 -110
- package/dist/entries/http/throttleMiddleware.js +41 -185
- package/dist/entries/http/uploads.js +9 -24
- package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
- package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
- package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
- package/dist/entries/mail/mailer.js +68 -78
- package/dist/entries/openapi/generator.js +33 -100
- package/dist/entries/queue/createAppQueue.js +416 -254
- package/dist/entries/queue/failedJobRepository.js +19 -8
- package/dist/entries/queue/failedJobService.js +1 -0
- package/dist/entries/queue/jobRunner.js +141 -66
- package/dist/entries/queue/publicQueue.js +411 -255
- package/dist/entries/queue/queueConfig.js +61 -0
- package/dist/entries/queue/queueHandoff.js +318 -0
- package/dist/entries/queue/queueMetrics.js +989 -1384
- package/dist/entries/queue/queueServices.js +133 -0
- package/dist/entries/queue/queueWorkerTransport.js +1703 -0
- package/dist/entries/queue/redisQueue.js +282 -180
- package/dist/entries/queue.js +6 -45
- package/dist/entries/runtime/application.js +1585 -0
- package/dist/entries/runtime/asyncContextStore.js +0 -16
- package/dist/entries/security/oauthState.js +35 -67
- package/dist/entries/security/publicReads.js +4 -4
- package/dist/entries/security/safeFetch.js +1 -0
- package/dist/entries/security/scimTenantTokens.js +3 -3
- package/dist/entries/security/tokenExpiry.js +2 -2
- package/dist/entries/security/totp.js +1 -87
- package/dist/entries/security/webhookSignature.js +2 -90
- package/dist/entries/storage/storage.js +120 -45
- package/dist/entries/tenant/databaseTenantContext.js +6 -907
- package/dist/entries/tenant/publicTenantHost.js +78 -0
- package/dist/entries/tenant/resolveTenant.js +14 -0
- package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
- package/dist/entries/tenant/tenancyConfig.js +1 -19
- package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
- package/dist/entries/tracing/tracingMiddleware.js +104 -173
- package/dist/entries/view/tokens.js +11 -0
- package/dist/framework/public-api.d.ts +62 -44
- package/dist/index.js +10433 -11347
- package/dist/internal/ormInternal.js +117 -0
- package/dist/internal/ormRuntime.js +5000 -0
- package/package.json +158 -46
- package/dist/core/database/bindConnection.d.ts +0 -1
- package/dist/core/database/boundConnection.d.ts +0 -5
- package/dist/core/database/defaultConnection.d.ts +0 -7
- package/dist/core/database/namedConnections.d.ts +0 -15
- package/dist/core/database/readOnlyCollector.d.ts +0 -7
- package/dist/core/database/repositoryConnection.d.ts +0 -4
- package/dist/core/database/transaction.d.ts +0 -23
- package/dist/core/database/transactionControl.d.ts +0 -6
- package/dist/core/events/deferredModelEvents.d.ts +0 -7
- package/dist/core/facades/index.d.ts +0 -10
- package/dist/core/runtime/applicationRegistry.d.ts +0 -18
- package/dist/entries/database/bindConnection.js +0 -1
- package/dist/entries/database/boundConnection.js +0 -1
- package/dist/entries/database/defaultConnection.js +0 -1
- package/dist/entries/database/namedConnections.js +0 -1
- package/dist/entries/database/repositoryConnection.js +0 -1
- package/dist/entries/database/transaction.js +0 -1
- package/dist/entries/facades.js +0 -711
- package/dist/entries/runtime/applicationRegistry.js +0 -1
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../../src/core/database/definitions.ts
|
|
3
|
+
import {
|
|
4
|
+
assertServiceToken
|
|
5
|
+
} from "@getstrata/core/contracts/token";
|
|
6
|
+
var definitionBrand = Symbol("database.definition");
|
|
7
|
+
var effectsBrand = Symbol("database.repository.effects");
|
|
8
|
+
function fields(input) {
|
|
9
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
10
|
+
throw new TypeError("Invalid database definition.");
|
|
11
|
+
const prototype = Object.getPrototypeOf(input);
|
|
12
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
13
|
+
throw new TypeError("Metadata must be a plain record.");
|
|
14
|
+
const copied = {};
|
|
15
|
+
for (const key of Reflect.ownKeys(input)) {
|
|
16
|
+
if (typeof key !== "string")
|
|
17
|
+
throw new TypeError("Invalid database definition field.");
|
|
18
|
+
const d = Object.getOwnPropertyDescriptor(input, key);
|
|
19
|
+
if (!d || !("value" in d))
|
|
20
|
+
throw new TypeError("Database metadata accessors are unsupported.");
|
|
21
|
+
copied[key] = d.value;
|
|
22
|
+
}
|
|
23
|
+
return copied;
|
|
24
|
+
}
|
|
25
|
+
function array(value) {
|
|
26
|
+
if (!Array.isArray(value))
|
|
27
|
+
throw new TypeError("Metadata requires an array.");
|
|
28
|
+
const result = [];
|
|
29
|
+
for (let index = 0;index < value.length; index++) {
|
|
30
|
+
const d = Object.getOwnPropertyDescriptor(value, String(index));
|
|
31
|
+
if (!d || !("value" in d))
|
|
32
|
+
throw new TypeError("Metadata array accessors and holes are unsupported.");
|
|
33
|
+
result.push(d.value);
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
function text(value) {
|
|
38
|
+
if (typeof value !== "string" || !value.trim())
|
|
39
|
+
throw new TypeError("Definition name must be nonempty.");
|
|
40
|
+
}
|
|
41
|
+
function brand(value) {
|
|
42
|
+
Object.defineProperty(value, definitionBrand, { value });
|
|
43
|
+
return Object.freeze(value);
|
|
44
|
+
}
|
|
45
|
+
function tokens(values) {
|
|
46
|
+
if (!Array.isArray(values))
|
|
47
|
+
throw new TypeError("Dependencies must be a tuple.");
|
|
48
|
+
const copied = array(values);
|
|
49
|
+
for (const token of copied)
|
|
50
|
+
assertServiceToken(token);
|
|
51
|
+
return Object.freeze(copied);
|
|
52
|
+
}
|
|
53
|
+
function snapshotTable(table) {
|
|
54
|
+
const v = fields(table);
|
|
55
|
+
text(v.name);
|
|
56
|
+
text(v.primaryKey);
|
|
57
|
+
if (!Array.isArray(v.columns) || !array(v.columns).every((c) => typeof c === "string") || !array(v.columns).includes(v.primaryKey))
|
|
58
|
+
throw new TypeError("Invalid table columns.");
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
...v,
|
|
61
|
+
columns: Object.freeze(array(v.columns)),
|
|
62
|
+
...v.defaultOrderBy === undefined ? {} : {
|
|
63
|
+
defaultOrderBy: Object.freeze(Array.isArray(v.defaultOrderBy) ? array(v.defaultOrderBy).map((o) => Object.freeze(fields(o))) : fields(v.defaultOrderBy))
|
|
64
|
+
},
|
|
65
|
+
...typeof v.softDeletes === "object" && v.softDeletes !== null ? { softDeletes: Object.freeze(fields(v.softDeletes)) } : {}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function defineRepository(s) {
|
|
69
|
+
fields(s);
|
|
70
|
+
text(s.name);
|
|
71
|
+
if (typeof s.create !== "function")
|
|
72
|
+
throw new TypeError("Repository requires a constructor.");
|
|
73
|
+
const hooks = s.hooks === undefined ? undefined : fields(s.hooks);
|
|
74
|
+
if (hooks && Object.entries(hooks).some(([key, value]) => !["transformQuery", "transformWrite", "hydrateRow"].includes(key) || typeof value !== "function"))
|
|
75
|
+
throw new TypeError("Invalid repository hook.");
|
|
76
|
+
return brand({
|
|
77
|
+
kind: "repository",
|
|
78
|
+
name: s.name,
|
|
79
|
+
table: snapshotTable(s.table),
|
|
80
|
+
dependencies: tokens(s.dependencies),
|
|
81
|
+
create: s.create,
|
|
82
|
+
effects: snapshotEffects(s.effects ?? []),
|
|
83
|
+
...hooks ? { hooks: Object.freeze(hooks) } : {}
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function defineModel(s) {
|
|
87
|
+
fields(s);
|
|
88
|
+
text(s.name);
|
|
89
|
+
assertDefinition(s.repository, "repository");
|
|
90
|
+
if (typeof s.construct !== "function")
|
|
91
|
+
throw new TypeError("Model requires a constructor.");
|
|
92
|
+
const attrs = fields(s.attributes);
|
|
93
|
+
if (Object.keys(attrs).some((key) => ![
|
|
94
|
+
"fillable",
|
|
95
|
+
"guarded",
|
|
96
|
+
"casts",
|
|
97
|
+
"timestamps",
|
|
98
|
+
"hidden",
|
|
99
|
+
"visible",
|
|
100
|
+
"appends",
|
|
101
|
+
"dehydrate"
|
|
102
|
+
].includes(key)))
|
|
103
|
+
throw new TypeError("Unknown model metadata.");
|
|
104
|
+
for (const key of ["fillable", "guarded", "hidden", "visible", "appends"])
|
|
105
|
+
if (attrs[key] !== undefined && !(key === "guarded" && attrs[key] === true) && !Array.isArray(attrs[key]))
|
|
106
|
+
throw new TypeError("Invalid model metadata array.");
|
|
107
|
+
if (attrs.dehydrate !== undefined && typeof attrs.dehydrate !== "function")
|
|
108
|
+
throw new TypeError("Invalid model dehydration hook.");
|
|
109
|
+
if (attrs.timestamps !== undefined && typeof attrs.timestamps !== "boolean")
|
|
110
|
+
throw new TypeError("Invalid timestamps metadata.");
|
|
111
|
+
for (const key of ["fillable", "guarded", "hidden", "visible", "appends"])
|
|
112
|
+
if (Array.isArray(attrs[key])) {
|
|
113
|
+
const values = array(attrs[key]);
|
|
114
|
+
for (const value of values)
|
|
115
|
+
text(value);
|
|
116
|
+
attrs[key] = Object.freeze(values);
|
|
117
|
+
}
|
|
118
|
+
if (attrs.casts) {
|
|
119
|
+
const casts = fields(attrs.casts);
|
|
120
|
+
if (Object.values(casts).some((value) => typeof value !== "string" || !["date", "datetime", "json", "bool", "boolean", "integer", "int", "hashed"].includes(value)))
|
|
121
|
+
throw new TypeError("Invalid model cast.");
|
|
122
|
+
attrs.casts = Object.freeze(casts);
|
|
123
|
+
}
|
|
124
|
+
const aliases = array(s.aliases ?? []);
|
|
125
|
+
for (const alias of aliases)
|
|
126
|
+
text(alias);
|
|
127
|
+
return brand({
|
|
128
|
+
kind: "model",
|
|
129
|
+
name: s.name,
|
|
130
|
+
aliases: Object.freeze(aliases),
|
|
131
|
+
repository: s.repository,
|
|
132
|
+
dependencies: tokens(s.dependencies),
|
|
133
|
+
attributes: Object.freeze(attrs),
|
|
134
|
+
observers: tokens(s.observers ?? []),
|
|
135
|
+
scopes: Object.freeze(array(s.scopes ?? []).map((scope) => {
|
|
136
|
+
if (typeof scope !== "function")
|
|
137
|
+
throw new TypeError("Scope must be a function.");
|
|
138
|
+
return scope;
|
|
139
|
+
})),
|
|
140
|
+
construct: s.construct
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
function assertDefinition(value, kind) {
|
|
144
|
+
if (!value || typeof value !== "object" || !Object.isFrozen(value) || Object.getOwnPropertyDescriptor(value, definitionBrand)?.value !== value || Object.getOwnPropertyDescriptor(value, "kind")?.value !== kind)
|
|
145
|
+
throw new TypeError("Expected original database definition.");
|
|
146
|
+
}
|
|
147
|
+
function snapshotEffects(effects) {
|
|
148
|
+
return Object.freeze(array(effects).map((effect) => {
|
|
149
|
+
fields(effect);
|
|
150
|
+
if (!["created", "updated", "deleted", "restored", "force-deleted"].includes(effect.action))
|
|
151
|
+
throw new TypeError("Invalid repository effect action.");
|
|
152
|
+
if (effect.transactional)
|
|
153
|
+
assertServiceToken(effect.transactional);
|
|
154
|
+
if (effect.afterCommit)
|
|
155
|
+
assertServiceToken(effect.afterCommit);
|
|
156
|
+
return Object.freeze({ ...effect });
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
function repositoryEffects(definition, effects) {
|
|
160
|
+
assertDefinition(definition, "repository");
|
|
161
|
+
const declaration = { definition, effects: snapshotEffects(effects) };
|
|
162
|
+
Object.defineProperty(declaration, effectsBrand, { value: declaration });
|
|
163
|
+
return Object.freeze(declaration);
|
|
164
|
+
}
|
|
165
|
+
function assertRepositoryEffectsDeclaration(value) {
|
|
166
|
+
if (!value || typeof value !== "object" || !Object.isFrozen(value) || Object.getOwnPropertyDescriptor(value, effectsBrand)?.value !== value)
|
|
167
|
+
throw new TypeError("Expected original repository effects declaration.");
|
|
168
|
+
}
|
|
169
|
+
export {
|
|
170
|
+
assertDefinition,
|
|
171
|
+
assertRepositoryEffectsDeclaration,
|
|
172
|
+
defineModel,
|
|
173
|
+
defineRepository,
|
|
174
|
+
repositoryEffects
|
|
175
|
+
};
|
|
@@ -1,123 +1,148 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// ../../src/core/database/errors.ts
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
class RecordNotFoundError extends Error {
|
|
4
|
+
constructor(message = "Record not found.") {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = new.target.name;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
var PERSISTENCE_MESSAGES = {
|
|
10
|
+
DATABASE_CONFIG_INVALID: "Database configuration is invalid.",
|
|
11
|
+
DATABASE_CONNECTION_UNKNOWN: "Database connection is not configured.",
|
|
12
|
+
DATABASE_TRANSACTION_SCOPE: "Database transaction scope is not active.",
|
|
13
|
+
DATABASE_UNSUPPORTED_CAPABILITY: "Database capability is not supported.",
|
|
14
|
+
DATABASE_TRANSACTION_ROLLBACK_ONLY: "Transaction rolled back after a failed database operation.",
|
|
15
|
+
DATABASE_TRANSACTION_FAILED: "Database transaction failed.",
|
|
16
|
+
DATABASE_TRANSACTION_UNKNOWN: "Database transaction outcome is unknown.",
|
|
17
|
+
DATABASE_POST_COMMIT_FAILED: "Database work failed after commit.",
|
|
18
|
+
DATABASE_UNIQUE_CONSTRAINT: "A record with these values already exists.",
|
|
19
|
+
DATABASE_FOREIGN_KEY_CONSTRAINT: "Referenced record does not exist.",
|
|
20
|
+
DATABASE_REFERENCED_RECORD: "Record is still referenced by other records.",
|
|
21
|
+
DATABASE_RELATED_RECORD_CONSTRAINT: "Operation conflicts with related records.",
|
|
22
|
+
DATABASE_NOT_NULL_CONSTRAINT: "Required field is missing.",
|
|
23
|
+
DATABASE_CHECK_CONSTRAINT: "Value violates a database constraint.",
|
|
24
|
+
DATABASE_OPERATION_FAILED: "Database operation failed."
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
class PersistenceError extends Error {
|
|
28
|
+
code;
|
|
29
|
+
constructor(code, options = {}) {
|
|
30
|
+
if (!Object.hasOwn(PERSISTENCE_MESSAGES, code))
|
|
31
|
+
throw new TypeError("Unknown persistence error code.");
|
|
32
|
+
super(PERSISTENCE_MESSAGES[code], Object.hasOwn(options, "cause") ? { cause: options.cause } : undefined);
|
|
33
|
+
this.name = "PersistenceError";
|
|
34
|
+
this.code = code;
|
|
35
|
+
const data = options.data;
|
|
36
|
+
if (data !== undefined) {
|
|
37
|
+
if (!["not-started", "committed", "rolled-back", "unknown"].includes(data))
|
|
38
|
+
throw new TypeError("Invalid transaction data disposition.");
|
|
39
|
+
Object.defineProperty(this, "data", { value: data, enumerable: true });
|
|
40
|
+
}
|
|
41
|
+
const result = options.result;
|
|
42
|
+
if (result !== undefined) {
|
|
43
|
+
if (result === null || typeof result !== "object" || Object.getPrototypeOf(result) !== Object.prototype && Object.getPrototypeOf(result) !== null)
|
|
44
|
+
throw new TypeError("Invalid persistence result observation.");
|
|
45
|
+
const ok = Object.getOwnPropertyDescriptor(result, "ok");
|
|
46
|
+
if (!ok || !("value" in ok) || typeof ok.value !== "boolean")
|
|
47
|
+
throw new TypeError("Invalid persistence result observation.");
|
|
48
|
+
const payload = Object.getOwnPropertyDescriptor(result, ok.value ? "value" : "error");
|
|
49
|
+
if (!payload || !("value" in payload))
|
|
50
|
+
throw new TypeError("Invalid persistence result observation.");
|
|
51
|
+
Object.defineProperty(this, "result", {
|
|
52
|
+
value: Object.freeze(ok.value ? { ok: true, value: payload.value } : { ok: false, error: payload.value }),
|
|
53
|
+
enumerable: false
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
10
58
|
function isPostgresError(error) {
|
|
11
59
|
return typeof error === "object" && error !== null && (("errno" in error) || ("code" in error));
|
|
12
60
|
}
|
|
13
61
|
function getPostgresSqlState(error) {
|
|
14
|
-
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno))
|
|
62
|
+
if (typeof error.errno === "string" && /^\d{5}$/.test(error.errno))
|
|
15
63
|
return error.errno;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
if (typeof error.code === "string" && /^\d{5}$/.test(error.code)) {
|
|
64
|
+
if (typeof error.errno === "number" && Number.isInteger(error.errno) && error.errno >= 1e4 && error.errno <= 99999)
|
|
65
|
+
return String(error.errno);
|
|
66
|
+
if (typeof error.code === "string" && /^\d{5}$/.test(error.code))
|
|
21
67
|
return error.code;
|
|
22
|
-
}
|
|
23
68
|
return;
|
|
24
69
|
}
|
|
25
|
-
|
|
26
|
-
1062: () => new ConflictError("A record with these values already exists."),
|
|
27
|
-
1451: () => new UnprocessableEntityError("Record is still referenced by other records."),
|
|
28
|
-
1452: () => new UnprocessableEntityError("Referenced record does not exist."),
|
|
29
|
-
1048: () => new BadRequestError("Required field is missing."),
|
|
30
|
-
3819: () => new BadRequestError("Value violates a database constraint.")
|
|
31
|
-
};
|
|
32
|
-
function mapSqliteError(error) {
|
|
33
|
-
const code = typeof error.code === "string" ? error.code : "";
|
|
34
|
-
if (!code.startsWith("SQLITE_")) {
|
|
35
|
-
return null;
|
|
36
|
-
}
|
|
37
|
-
if (code === "SQLITE_CONSTRAINT_UNIQUE" || code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
|
|
38
|
-
return new ConflictError("A record with these values already exists.");
|
|
39
|
-
}
|
|
40
|
-
if (code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
|
|
41
|
-
return new UnprocessableEntityError("Operation conflicts with related records.");
|
|
42
|
-
}
|
|
43
|
-
if (code === "SQLITE_CONSTRAINT_NOTNULL") {
|
|
44
|
-
return new BadRequestError("Required field is missing.");
|
|
45
|
-
}
|
|
46
|
-
if (code.startsWith("SQLITE_CONSTRAINT")) {
|
|
47
|
-
return new BadRequestError("Value violates a database constraint.");
|
|
48
|
-
}
|
|
49
|
-
return new InternalServerError("Database operation failed.");
|
|
50
|
-
}
|
|
51
|
-
function mapMysqlError(error) {
|
|
70
|
+
function driverErrorCode(error) {
|
|
52
71
|
const code = typeof error.code === "string" ? error.code : "";
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
return
|
|
63
|
-
}
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
72
|
+
if (code.startsWith("SQLITE_")) {
|
|
73
|
+
if (code === "SQLITE_CONSTRAINT_UNIQUE" || code === "SQLITE_CONSTRAINT_PRIMARYKEY")
|
|
74
|
+
return "DATABASE_UNIQUE_CONSTRAINT";
|
|
75
|
+
if (code === "SQLITE_CONSTRAINT_FOREIGNKEY")
|
|
76
|
+
return "DATABASE_RELATED_RECORD_CONSTRAINT";
|
|
77
|
+
if (code === "SQLITE_CONSTRAINT_NOTNULL")
|
|
78
|
+
return "DATABASE_NOT_NULL_CONSTRAINT";
|
|
79
|
+
if (code.startsWith("SQLITE_CONSTRAINT"))
|
|
80
|
+
return "DATABASE_CHECK_CONSTRAINT";
|
|
81
|
+
return "DATABASE_OPERATION_FAILED";
|
|
82
|
+
}
|
|
83
|
+
if (code.startsWith("ER_")) {
|
|
84
|
+
switch (error.errno) {
|
|
85
|
+
case 1062:
|
|
86
|
+
return "DATABASE_UNIQUE_CONSTRAINT";
|
|
87
|
+
case 1451:
|
|
88
|
+
return "DATABASE_REFERENCED_RECORD";
|
|
89
|
+
case 1452:
|
|
90
|
+
return "DATABASE_FOREIGN_KEY_CONSTRAINT";
|
|
91
|
+
case 1048:
|
|
92
|
+
return "DATABASE_NOT_NULL_CONSTRAINT";
|
|
93
|
+
case 3819:
|
|
94
|
+
return "DATABASE_CHECK_CONSTRAINT";
|
|
95
|
+
default:
|
|
96
|
+
return "DATABASE_OPERATION_FAILED";
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
switch (getPostgresSqlState(error)) {
|
|
77
100
|
case "23505":
|
|
78
|
-
|
|
79
|
-
console.error("[database] unique violation", error.detail);
|
|
80
|
-
}
|
|
81
|
-
return new ConflictError("A record with these values already exists.");
|
|
101
|
+
return "DATABASE_UNIQUE_CONSTRAINT";
|
|
82
102
|
case "23503":
|
|
83
|
-
|
|
84
|
-
console.error("[database] foreign-key violation", error.detail);
|
|
85
|
-
}
|
|
86
|
-
return new UnprocessableEntityError("Operation conflicts with related records.");
|
|
103
|
+
return "DATABASE_RELATED_RECORD_CONSTRAINT";
|
|
87
104
|
case "23502":
|
|
88
|
-
|
|
89
|
-
console.error("[database] not-null violation", error.detail);
|
|
90
|
-
}
|
|
91
|
-
return new BadRequestError("Required field is missing.");
|
|
105
|
+
return "DATABASE_NOT_NULL_CONSTRAINT";
|
|
92
106
|
case "23514":
|
|
93
|
-
|
|
94
|
-
console.error("[database] check violation", error.detail);
|
|
95
|
-
}
|
|
96
|
-
return new BadRequestError("Value violates a database constraint.");
|
|
107
|
+
return "DATABASE_CHECK_CONSTRAINT";
|
|
97
108
|
default:
|
|
98
|
-
return
|
|
109
|
+
return "DATABASE_OPERATION_FAILED";
|
|
99
110
|
}
|
|
100
111
|
}
|
|
112
|
+
function mapDatabaseError(error) {
|
|
113
|
+
if (error instanceof PersistenceError)
|
|
114
|
+
return error;
|
|
115
|
+
return new PersistenceError(isPostgresError(error) ? driverErrorCode(error) : "DATABASE_OPERATION_FAILED", { cause: error });
|
|
116
|
+
}
|
|
117
|
+
function isNativeDatabaseError(error) {
|
|
118
|
+
if (!isPostgresError(error))
|
|
119
|
+
return false;
|
|
120
|
+
const code = typeof error.code === "string" ? error.code : "";
|
|
121
|
+
return code.startsWith("SQLITE_") || code.startsWith("ER_") || code === "ERR_POSTGRES_SERVER_ERROR" || /^\d{5}$/.test(code) || code === "" && getPostgresSqlState(error) !== undefined;
|
|
122
|
+
}
|
|
101
123
|
async function withDatabaseErrorHandling(operation) {
|
|
102
124
|
try {
|
|
103
125
|
return await operation();
|
|
104
126
|
} catch (error) {
|
|
105
|
-
|
|
127
|
+
if (error instanceof PersistenceError || isNativeDatabaseError(error))
|
|
128
|
+
throw mapDatabaseError(error);
|
|
129
|
+
throw error;
|
|
106
130
|
}
|
|
107
131
|
}
|
|
108
132
|
function isUniqueConstraintError(error) {
|
|
109
|
-
if (
|
|
133
|
+
if (error instanceof PersistenceError)
|
|
134
|
+
return error.code === "DATABASE_UNIQUE_CONSTRAINT";
|
|
135
|
+
if (!isPostgresError(error))
|
|
110
136
|
return false;
|
|
111
|
-
|
|
112
|
-
if (error.code === "SQLITE_CONSTRAINT_UNIQUE" || error.code === "SQLITE_CONSTRAINT_PRIMARYKEY") {
|
|
137
|
+
if (error.code === "SQLITE_CONSTRAINT_UNIQUE" || error.code === "SQLITE_CONSTRAINT_PRIMARYKEY")
|
|
113
138
|
return true;
|
|
114
|
-
|
|
115
|
-
if (error.errno === 1062) {
|
|
139
|
+
if (error.errno === 1062)
|
|
116
140
|
return true;
|
|
117
|
-
}
|
|
118
141
|
return getPostgresSqlState(error) === "23505";
|
|
119
142
|
}
|
|
120
143
|
export {
|
|
144
|
+
PersistenceError,
|
|
145
|
+
RecordNotFoundError,
|
|
121
146
|
isPostgresError,
|
|
122
147
|
isUniqueConstraintError,
|
|
123
148
|
mapDatabaseError,
|
|
@@ -17,6 +17,32 @@ function foreignKeyFromTable(tableName) {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
// ../../src/core/database/factory.ts
|
|
20
|
+
var construction = Symbol("factory.construction");
|
|
21
|
+
function defineFactory(spec) {
|
|
22
|
+
let create;
|
|
23
|
+
if ("initialState" in spec) {
|
|
24
|
+
const initialState = spec.initialState.bind(spec);
|
|
25
|
+
const forkState = spec.forkState.bind(spec);
|
|
26
|
+
const construct = spec.construct.bind(spec);
|
|
27
|
+
create = (dependencies) => {
|
|
28
|
+
const build = (state) => ({
|
|
29
|
+
behavior: construct(state, dependencies),
|
|
30
|
+
fork: () => build(forkState(state))
|
|
31
|
+
});
|
|
32
|
+
return build(initialState());
|
|
33
|
+
};
|
|
34
|
+
} else {
|
|
35
|
+
const construct = spec.construct.bind(spec);
|
|
36
|
+
create = (dependencies) => {
|
|
37
|
+
const build = () => ({
|
|
38
|
+
behavior: construct(dependencies),
|
|
39
|
+
fork: build
|
|
40
|
+
});
|
|
41
|
+
return build();
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
return Object.freeze({ [construction]: create });
|
|
45
|
+
}
|
|
20
46
|
function inferFactoryForeignKey(parent, explicit) {
|
|
21
47
|
if (explicit) {
|
|
22
48
|
if (explicit.endsWith("_id")) {
|
|
@@ -31,6 +57,7 @@ function inferFactoryForeignKey(parent, explicit) {
|
|
|
31
57
|
}
|
|
32
58
|
|
|
33
59
|
class Factory {
|
|
60
|
+
instance;
|
|
34
61
|
quantity = 1;
|
|
35
62
|
counted = false;
|
|
36
63
|
sequenceIndex = 0;
|
|
@@ -40,17 +67,21 @@ class Factory {
|
|
|
40
67
|
children = [];
|
|
41
68
|
afterMakingCallbacks = [];
|
|
42
69
|
afterCreatingCallbacks = [];
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
throw new Error("Factory definition must be implemented by subclass.");
|
|
70
|
+
constructor(instance) {
|
|
71
|
+
this.instance = instance;
|
|
46
72
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
73
|
+
static from(definition, dependencies) {
|
|
74
|
+
return new Factory(definition[construction](dependencies));
|
|
75
|
+
}
|
|
76
|
+
fork() {
|
|
77
|
+
const next = new Factory(this.instance.fork());
|
|
78
|
+
next.quantity = this.quantity;
|
|
79
|
+
next.counted = this.counted;
|
|
80
|
+
next.sequenceIndex = this.sequenceIndex;
|
|
50
81
|
next.stateTransforms = [...this.stateTransforms];
|
|
51
82
|
next.sequenceItems = [...this.sequenceItems];
|
|
52
83
|
next.parentAssociations = [...this.parentAssociations];
|
|
53
|
-
next.children =
|
|
84
|
+
next.children = this.children.map((child) => ({ ...child, factory: child.factory.fork() }));
|
|
54
85
|
next.afterMakingCallbacks = [...this.afterMakingCallbacks];
|
|
55
86
|
next.afterCreatingCallbacks = [...this.afterCreatingCallbacks];
|
|
56
87
|
return next;
|
|
@@ -59,22 +90,28 @@ class Factory {
|
|
|
59
90
|
if (!Number.isInteger(quantity) || quantity < 1) {
|
|
60
91
|
throw new Error("Factory.count() requires a positive integer.");
|
|
61
92
|
}
|
|
62
|
-
const next = this.
|
|
93
|
+
const next = this.fork();
|
|
63
94
|
next.quantity = quantity;
|
|
64
95
|
next.counted = true;
|
|
65
96
|
return next;
|
|
66
97
|
}
|
|
67
98
|
state(state) {
|
|
68
|
-
const next = this.
|
|
69
|
-
next.stateTransforms = [
|
|
99
|
+
const next = this.fork();
|
|
100
|
+
next.stateTransforms = [
|
|
101
|
+
...this.stateTransforms,
|
|
102
|
+
typeof state === "function" ? state : { ...state }
|
|
103
|
+
];
|
|
70
104
|
return next;
|
|
71
105
|
}
|
|
72
106
|
sequence(...items) {
|
|
73
107
|
if (items.length === 0) {
|
|
74
108
|
throw new Error("Factory.sequence() requires at least one attribute set.");
|
|
75
109
|
}
|
|
76
|
-
const next = this.
|
|
77
|
-
next.sequenceItems = [
|
|
110
|
+
const next = this.fork();
|
|
111
|
+
next.sequenceItems = [
|
|
112
|
+
...this.sequenceItems,
|
|
113
|
+
...items.map((item) => typeof item === "function" ? item : { ...item })
|
|
114
|
+
];
|
|
78
115
|
return next;
|
|
79
116
|
}
|
|
80
117
|
for(parent, foreignKey) {
|
|
@@ -82,7 +119,7 @@ class Factory {
|
|
|
82
119
|
throw new Error("Factory.for() requires a parent with an id.");
|
|
83
120
|
}
|
|
84
121
|
const key = inferFactoryForeignKey(parent, foreignKey);
|
|
85
|
-
const next = this.
|
|
122
|
+
const next = this.fork();
|
|
86
123
|
next.parentAssociations = [...this.parentAssociations, { foreignKey: key, value: parent.id }];
|
|
87
124
|
return next;
|
|
88
125
|
}
|
|
@@ -90,20 +127,20 @@ class Factory {
|
|
|
90
127
|
return this.for(parent, foreignKey);
|
|
91
128
|
}
|
|
92
129
|
afterMaking(callback) {
|
|
93
|
-
const next = this.
|
|
130
|
+
const next = this.fork();
|
|
94
131
|
next.afterMakingCallbacks = [...this.afterMakingCallbacks, callback];
|
|
95
132
|
return next;
|
|
96
133
|
}
|
|
97
134
|
afterCreating(callback) {
|
|
98
|
-
const next = this.
|
|
135
|
+
const next = this.fork();
|
|
99
136
|
next.afterCreatingCallbacks = [...this.afterCreatingCallbacks, callback];
|
|
100
137
|
return next;
|
|
101
138
|
}
|
|
102
139
|
has(factory, foreignKey) {
|
|
103
|
-
const next = this.
|
|
140
|
+
const next = this.fork();
|
|
104
141
|
next.children = [
|
|
105
142
|
...this.children,
|
|
106
|
-
{ factory, foreignKey }
|
|
143
|
+
{ factory: factory.fork(), foreignKey }
|
|
107
144
|
];
|
|
108
145
|
return next;
|
|
109
146
|
}
|
|
@@ -124,7 +161,7 @@ class Factory {
|
|
|
124
161
|
return records;
|
|
125
162
|
}
|
|
126
163
|
makeOne(overrides = {}) {
|
|
127
|
-
let record = { ...this.definition() };
|
|
164
|
+
let record = { ...this.instance.behavior.definition() };
|
|
128
165
|
for (const state of this.stateTransforms) {
|
|
129
166
|
const patch = typeof state === "function" ? state(record) : state;
|
|
130
167
|
record = { ...record, ...patch };
|
|
@@ -152,7 +189,13 @@ class Factory {
|
|
|
152
189
|
}
|
|
153
190
|
async persistCreated(record) {
|
|
154
191
|
const created = await this.persist(this.insertable(record));
|
|
155
|
-
|
|
192
|
+
const children = this.children.map((child) => child.factory.for(created, child.foreignKey));
|
|
193
|
+
const outcomes = await Promise.allSettled(children.map((child) => Promise.resolve().then(() => child.create())));
|
|
194
|
+
const errors = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
|
|
195
|
+
if (errors.length === 1)
|
|
196
|
+
throw errors[0];
|
|
197
|
+
if (errors.length)
|
|
198
|
+
throw new AggregateError(errors, "Factory children failed.");
|
|
156
199
|
for (const callback of this.afterCreatingCallbacks) {
|
|
157
200
|
await callback(created);
|
|
158
201
|
}
|
|
@@ -166,16 +209,12 @@ class Factory {
|
|
|
166
209
|
return values;
|
|
167
210
|
}
|
|
168
211
|
async persist(values) {
|
|
169
|
-
if (this.
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
return created.toObject();
|
|
173
|
-
}
|
|
174
|
-
return created;
|
|
175
|
-
}
|
|
176
|
-
throw new Error("Factory.persist() must be implemented to use create().");
|
|
212
|
+
if (!this.instance.behavior.persist)
|
|
213
|
+
throw new Error("Factory.persist() must be supplied to use create().");
|
|
214
|
+
return this.instance.behavior.persist(values);
|
|
177
215
|
}
|
|
178
216
|
}
|
|
179
217
|
export {
|
|
180
|
-
Factory
|
|
218
|
+
Factory,
|
|
219
|
+
defineFactory
|
|
181
220
|
};
|