domainkit 0.8.0 → 0.9.0
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/README.md +213 -41
- package/dist/Approval.mjs +34 -0
- package/dist/Approval.mjs.map +1 -0
- package/dist/Cleanup.mjs +97 -0
- package/dist/Cleanup.mjs.map +1 -0
- package/dist/Cloudflare.mjs +225 -0
- package/dist/Cloudflare.mjs.map +1 -0
- package/dist/Connect.mjs +463 -0
- package/dist/Connect.mjs.map +1 -0
- package/dist/Custody.mjs +64 -0
- package/dist/Custody.mjs.map +1 -0
- package/dist/DnsRecord.mjs +213 -0
- package/dist/DnsRecord.mjs.map +1 -0
- package/dist/DomainKit.mjs +34 -0
- package/dist/DomainKit.mjs.map +1 -0
- package/dist/DomainName.mjs +100 -0
- package/dist/DomainName.mjs.map +1 -0
- package/dist/Plan.mjs +102 -0
- package/dist/Plan.mjs.map +1 -0
- package/dist/Principal.mjs +23 -0
- package/dist/Principal.mjs.map +1 -0
- package/dist/Provider.mjs +130 -0
- package/dist/Provider.mjs.map +1 -0
- package/dist/Providers.mjs +40 -0
- package/dist/Providers.mjs.map +1 -0
- package/dist/Provision.mjs +93 -0
- package/dist/Provision.mjs.map +1 -0
- package/dist/Reason.mjs +162 -0
- package/dist/Reason.mjs.map +1 -0
- package/dist/Receipt.mjs +71 -0
- package/dist/Receipt.mjs.map +1 -0
- package/dist/Resolver.mjs +75 -0
- package/dist/Resolver.mjs.map +1 -0
- package/dist/Server.mjs +516 -0
- package/dist/Server.mjs.map +1 -0
- package/dist/Storage.mjs +236 -0
- package/dist/Storage.mjs.map +1 -0
- package/dist/Testing.mjs +226 -0
- package/dist/Testing.mjs.map +1 -0
- package/dist/Transport.mjs +187 -0
- package/dist/Transport.mjs.map +1 -0
- package/dist/Vercel.mjs +116 -0
- package/dist/Vercel.mjs.map +1 -0
- package/dist/Verify.mjs +292 -0
- package/dist/Verify.mjs.map +1 -0
- package/dist/{rolldown-runtime-D7D4PA-g.mjs → _virtual/_rolldown/runtime.mjs} +1 -1
- package/dist/entry/client.mjs +2 -0
- package/dist/entry/server.mjs +2 -0
- package/dist/entry/testing.mjs +3 -0
- package/dist/index.mjs +33 -462
- package/dist/index.mjs.map +1 -1
- package/dist/internal/aes.mjs +61 -0
- package/dist/internal/aes.mjs.map +1 -0
- package/dist/internal/attempts.mjs +284 -0
- package/dist/internal/attempts.mjs.map +1 -0
- package/dist/internal/cloudflare/client.mjs +100 -0
- package/dist/internal/cloudflare/client.mjs.map +1 -0
- package/dist/internal/cloudflare/protocol.mjs +59 -0
- package/dist/internal/cloudflare/protocol.mjs.map +1 -0
- package/dist/internal/cloudflare/records.mjs +156 -0
- package/dist/internal/cloudflare/records.mjs.map +1 -0
- package/dist/internal/config.mjs +13 -0
- package/dist/internal/config.mjs.map +1 -0
- package/dist/internal/conformance/provider.mjs +207 -0
- package/dist/internal/conformance/provider.mjs.map +1 -0
- package/dist/internal/conformance/storage.mjs +428 -0
- package/dist/internal/conformance/storage.mjs.map +1 -0
- package/dist/internal/digest.mjs +25 -0
- package/dist/internal/digest.mjs.map +1 -0
- package/dist/internal/doh.mjs +152 -0
- package/dist/internal/doh.mjs.map +1 -0
- package/dist/internal/error.mjs +69 -0
- package/dist/internal/error.mjs.map +1 -0
- package/dist/internal/http.mjs +89 -0
- package/dist/internal/http.mjs.map +1 -0
- package/dist/internal/ids.mjs +8 -0
- package/dist/internal/ids.mjs.map +1 -0
- package/dist/internal/oauth.mjs +113 -0
- package/dist/internal/oauth.mjs.map +1 -0
- package/dist/internal/planner.mjs +88 -0
- package/dist/internal/planner.mjs.map +1 -0
- package/dist/internal/provider-async.mjs +83 -0
- package/dist/internal/provider-async.mjs.map +1 -0
- package/dist/internal/storage-memory.mjs +302 -0
- package/dist/internal/storage-memory.mjs.map +1 -0
- package/dist/internal/vercel/client.mjs +122 -0
- package/dist/internal/vercel/client.mjs.map +1 -0
- package/dist/internal/vercel/protocol.mjs +80 -0
- package/dist/internal/vercel/protocol.mjs.map +1 -0
- package/dist/internal/vercel/records.mjs +151 -0
- package/dist/internal/vercel/records.mjs.map +1 -0
- package/dist/package.mjs +6 -0
- package/dist/package.mjs.map +1 -0
- package/dist/types/Approval.d.ts +26 -0
- package/dist/types/Cleanup.d.ts +41 -0
- package/dist/types/Cloudflare.d.ts +36 -0
- package/dist/types/Connect.d.ts +506 -0
- package/dist/types/Custody.d.ts +38 -0
- package/dist/types/DnsRecord.d.ts +158 -0
- package/dist/types/DomainKit.d.ts +31 -0
- package/dist/types/DomainName.d.ts +27 -0
- package/dist/types/Plan.d.ts +76 -0
- package/dist/types/Principal.d.ts +18 -0
- package/dist/types/Provider.d.ts +248 -0
- package/dist/types/Providers.d.ts +16 -0
- package/dist/types/Provision.d.ts +75 -0
- package/dist/types/Reason.d.ts +118 -0
- package/dist/types/Receipt.d.ts +55 -0
- package/dist/types/Resolver.d.ts +135 -0
- package/dist/types/Server.d.ts +6523 -0
- package/dist/types/Storage.d.ts +314 -0
- package/dist/types/Testing.d.ts +84 -0
- package/dist/types/Transport.d.ts +124 -0
- package/dist/types/Vercel.d.ts +25 -0
- package/dist/types/Verify.d.ts +109 -0
- package/dist/types/entry/client.d.ts +2 -0
- package/dist/types/entry/server.d.ts +2 -0
- package/dist/types/entry/testing.d.ts +3 -0
- package/dist/types/index.d.ts +21 -0
- package/dist/types/internal/aes.d.ts +8 -0
- package/dist/types/internal/attempts.d.ts +40 -0
- package/dist/types/internal/cloudflare/client.d.ts +23 -0
- package/dist/types/internal/cloudflare/protocol.d.ts +71 -0
- package/dist/types/internal/cloudflare/records.d.ts +8 -0
- package/dist/types/internal/config.d.ts +4 -0
- package/dist/types/internal/conformance/provider.d.ts +12 -0
- package/dist/types/internal/conformance/storage.d.ts +14 -0
- package/dist/types/internal/digest.d.ts +10 -0
- package/dist/types/internal/doh.d.ts +19 -0
- package/dist/types/internal/error.d.ts +24 -0
- package/dist/types/internal/http.d.ts +27 -0
- package/dist/types/internal/ids.d.ts +3 -0
- package/dist/types/internal/oauth.d.ts +58 -0
- package/dist/types/internal/planner.d.ts +22 -0
- package/dist/types/internal/provider-async.d.ts +78 -0
- package/dist/types/internal/storage-memory.d.ts +2 -0
- package/dist/types/internal/vercel/client.d.ts +29 -0
- package/dist/types/internal/vercel/protocol.d.ts +124 -0
- package/dist/types/internal/vercel/records.d.ts +7 -0
- package/package.json +88 -12
- package/dist/canonical-json-CQYKsZw7.mjs +0 -310
- package/dist/canonical-json-CQYKsZw7.mjs.map +0 -1
- package/dist/connect-D-X8T9W8.d.mts +0 -1597
- package/dist/connect-oI8hcMxc.mjs +0 -185
- package/dist/connect-oI8hcMxc.mjs.map +0 -1
- package/dist/connection-Dp6ZdSo8.d.mts +0 -186
- package/dist/connection-api-lqG1nBtD.d.mts +0 -26
- package/dist/index.d.mts +0 -1551
- package/dist/managed-dns-connections-C3A_GBaz.mjs +0 -99
- package/dist/managed-dns-connections-C3A_GBaz.mjs.map +0 -1
- package/dist/promise.d.mts +0 -378
- package/dist/promise.mjs +0 -598
- package/dist/promise.mjs.map +0 -1
- package/dist/resolver-BeGz1ukw.mjs +0 -921
- package/dist/resolver-BeGz1ukw.mjs.map +0 -1
- package/dist/resolver-xoSwyXDJ.d.mts +0 -3734
- package/dist/server.d.mts +0 -128
- package/dist/server.mjs +0 -319
- package/dist/server.mjs.map +0 -1
- package/dist/testing.d.mts +0 -62
- package/dist/testing.mjs +0 -507
- package/dist/testing.mjs.map +0 -1
- package/dist/verify-DvGPb5C9.mjs +0 -2402
- package/dist/verify-DvGPb5C9.mjs.map +0 -1
- package/dist/verify-FpunAcM7.d.mts +0 -1335
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Server.mjs","names":["Storage.AuthMethod","DnsRecord.Model","Plan.OperationId","Plan.Model","Storage.AttemptStatus","Approval.Model","Receipt.Model","Storage.Rejection","Storage.Overall","Storage.RequirementStatus","Verify.Evidence","Verify.HostEvidence","Plan.PlanId","Approval.ApprovalId","Receipt.ReceiptId","Errors.fail","Reason.InvalidInput","Errors.DomainKitError","Connect.Service","Provision.Service","Cleanup.Service","Verify.Service","Storage.Service","Principal.Service","Reason.NotFound"],"sources":["../src/Server.ts"],"sourcesContent":["/**\n * domainkit/server — the whole lifecycle as one HttpApi group the host mounts.\n *\n * const Api = HttpApi.make(\"app\").add(Server.group)\n * const ApiLive = HttpApiBuilder.layer(Api).pipe(\n * Layer.provide([Server.layer(Api), DomainKitLive, IdentityLive]),\n * )\n *\n * The host provides `Identity` (request -> `Principal.Interface`). Everything else comes from\n * `DomainKit.layer`. Non-HttpApi hosts use `toWebHandler`. The group carries no prefix of its\n * own, so `group.prefix(\"/internal/dns\")` or a host router mount is all a different base path\n * takes; callback URLs follow the mount.\n */\nimport { Context, Effect, Layer, Option, Schema } from \"effect\";\nimport * as HttpRouter from \"effect/unstable/http/HttpRouter\";\nimport * as HttpServer from \"effect/unstable/http/HttpServer\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\nimport * as HttpApi from \"effect/unstable/httpapi/HttpApi\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\nimport * as HttpApiEndpoint from \"effect/unstable/httpapi/HttpApiEndpoint\";\nimport * as HttpApiGroup from \"effect/unstable/httpapi/HttpApiGroup\";\nimport * as HttpApiSchema from \"effect/unstable/httpapi/HttpApiSchema\";\n\nimport * as Approval from \"./Approval.ts\";\nimport * as Cleanup from \"./Cleanup.ts\";\nimport * as Connect from \"./Connect.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Providers from \"./Providers.ts\";\nimport * as Provision from \"./Provision.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport * as Receipt from \"./Receipt.ts\";\nimport * as Storage from \"./Storage.ts\";\nimport * as Verify from \"./Verify.ts\";\n\n/** The only service a host must implement for the server. */\nexport interface IdentityService {\n readonly principal: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<Principal.Interface, Errors.DomainKitError>;\n /**\n * Which routes this principal may reach, checked after `principal` on every request. Fail with\n * reason `Forbidden` for the 403 a UI expects. Without it every authenticated principal reaches\n * every route, which is the right default for a host whose own middleware already gates the\n * mount.\n */\n readonly authorize?: (\n principal: Principal.Interface,\n endpoint: EndpointName,\n ) => Effect.Effect<void, Errors.DomainKitError>;\n}\n\nexport class Identity extends Context.Service<Identity, IdentityService>()(\n \"@domainkit/server/Identity\",\n) {}\n\n// ---------------------------------------------------------------------------------------------\n// Wire schemas (the transport contract `domainkit/client` and `@domainkit/react` consume)\n// ---------------------------------------------------------------------------------------------\n\nexport const ConnectionStatus = Schema.Literals([\"disconnected\", \"connected\", \"reconnect\"]);\nexport type ConnectionStatus = typeof ConnectionStatus.Type;\n\n/** One value a token method needs, so a form renders without knowing the provider. */\nexport const Field = Schema.Struct({\n name: Schema.String,\n required: Schema.Boolean,\n secret: Schema.Boolean,\n});\nexport type Field = typeof Field.Type;\n\n/** How a provider can be connected; `fields` is `null` for the interactive methods. */\nexport const MethodDescriptor = Schema.Struct({\n kind: Storage.AuthMethod,\n label: Schema.String,\n docsUrl: Schema.NullOr(Schema.String),\n fields: Schema.NullOr(Schema.Array(Field)),\n});\nexport type MethodDescriptor = typeof MethodDescriptor.Type;\n\n/** Everything the UI needs about a domain, flattened; provider context never crosses the wire. */\nexport const Snapshot = Schema.Struct({\n domain: Schema.String,\n attachmentId: Schema.NullOr(Schema.String),\n connectionId: Schema.NullOr(Schema.String),\n provider: Schema.NullOr(Schema.String),\n method: Schema.NullOr(Storage.AuthMethod),\n status: ConnectionStatus,\n lastReceiptId: Schema.NullOr(Schema.String),\n reusable: Schema.Array(\n Schema.Struct({\n connectionId: Schema.String,\n provider: Schema.String,\n method: Storage.AuthMethod,\n }),\n ),\n providers: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n name: Schema.String,\n methods: Schema.Array(MethodDescriptor),\n }),\n ),\n});\nexport type Snapshot = typeof Snapshot.Type;\n\n/**\n * How the client asks to connect. `values` is keyed by the provider's declared token fields, as\n * `Snapshot.providers[].methods[].fields` names them. Secrets are plaintext in transit and never\n * come back out.\n */\nexport class Token extends Schema.TaggedClass<Token>(\"@domainkit/server/Method/Token\")(\"Token\", {\n values: Schema.Record(Schema.String, Schema.String),\n}) {}\nexport class OAuth extends Schema.TaggedClass<OAuth>(\"@domainkit/server/Method/OAuth\")(\"OAuth\", {\n returnTo: Schema.optionalKey(Schema.String),\n}) {}\nexport class Integration extends Schema.TaggedClass<Integration>(\n \"@domainkit/server/Method/Integration\",\n)(\"Integration\", { returnTo: Schema.optionalKey(Schema.String) }) {}\nexport const Method = Schema.Union([Token, OAuth, Integration]);\nexport type Method = typeof Method.Type;\n\nexport const StartPayload = Schema.Struct({\n domain: Schema.String,\n provider: Schema.String,\n method: Method,\n});\nexport type StartPayload = typeof StartPayload.Type;\n\n/** A zone the connection can serve, named for a customer to pick from. */\nexport class Candidate extends Schema.Class<Candidate>(\"@domainkit/server/Candidate\")({\n zone: Schema.String,\n label: Schema.String,\n}) {}\n\nexport class Connected extends Schema.TaggedClass<Connected>(\"@domainkit/server/Started/Connected\")(\n \"Connected\",\n { snapshot: Snapshot },\n) {}\nexport class Redirect extends Schema.TaggedClass<Redirect>(\"@domainkit/server/Started/Redirect\")(\n \"Redirect\",\n { authorizationUrl: Schema.String },\n) {}\nexport class SelectionRequired extends Schema.TaggedClass<SelectionRequired>(\n \"@domainkit/server/Started/SelectionRequired\",\n)(\"SelectionRequired\", { connectionId: Schema.String, candidates: Schema.Array(Candidate) }) {}\nexport const Started = Schema.Union([Connected, Redirect, SelectionRequired]);\nexport type Started = typeof Started.Type;\n\n/**\n * Which of the principal's connections already reaches a domain. The class names carry a\n * `Discovery` prefix because `Started` owns the unprefixed `SelectionRequired`; the wire tags are\n * the ones `Connect.Discovery` uses.\n */\nexport class DiscoveryResolved extends Schema.TaggedClass<DiscoveryResolved>(\n \"@domainkit/server/Discovery/Resolved\",\n)(\"Resolved\", { connectionId: Schema.String, zone: Schema.String, label: Schema.String }) {}\nexport class DiscoverySelectionRequired extends Schema.TaggedClass<DiscoverySelectionRequired>(\n \"@domainkit/server/Discovery/SelectionRequired\",\n)(\"SelectionRequired\", {\n candidates: Schema.Array(\n Schema.Struct({ connectionId: Schema.String, zone: Schema.String, label: Schema.String }),\n ),\n}) {}\nexport class DiscoveryNotFound extends Schema.TaggedClass<DiscoveryNotFound>(\n \"@domainkit/server/Discovery/NotFound\",\n)(\"NotFound\", { nameservers: Schema.Array(Schema.String) }) {}\nexport const Discovery = Schema.Union([\n DiscoveryResolved,\n DiscoverySelectionRequired,\n DiscoveryNotFound,\n]);\nexport type Discovery = typeof Discovery.Type;\n\nexport const AttachPayload = Schema.Struct({\n domain: Schema.String,\n /** Which candidate zone to attach when `SelectionRequired` came back. */\n zone: Schema.optionalKey(Schema.String),\n});\nexport type AttachPayload = typeof AttachPayload.Type;\n\nexport const PlanPayload = Schema.Struct({\n requirements: Schema.Array(DnsRecord.Model),\n});\nexport type PlanPayload = typeof PlanPayload.Type;\n\nexport const ObservePayload = Schema.Struct({\n /** Records to observe instead of the attachment's receipt; required for an unattached domain. */\n requirements: Schema.optionalKey(Schema.Array(DnsRecord.Model)),\n});\nexport type ObservePayload = typeof ObservePayload.Type;\n\nexport const ApprovePayload = Schema.Struct({\n /** A subset of the plan's writes; omit to approve every write. */\n operationIds: Schema.optionalKey(Schema.Array(Plan.OperationId)),\n});\nexport type ApprovePayload = typeof ApprovePayload.Type;\n\nexport const RejectPayload = Schema.Struct({\n /** Why the customer declined, for the audit trail. */\n reason: Schema.optionalKey(Schema.String),\n});\nexport type RejectPayload = typeof RejectPayload.Type;\n\n/** One durable plan -> approval -> receipt lifecycle, as `GET /plans/:planId` returns it. */\nexport const Attempt = Schema.Struct({\n plan: Plan.Model,\n status: Storage.AttemptStatus,\n approval: Schema.NullOr(Approval.Model),\n receipt: Schema.NullOr(Receipt.Model),\n rejection: Schema.NullOr(Storage.Rejection),\n});\nexport type Attempt = typeof Attempt.Type;\n\n/** `Verify.Readiness` on the wire; timestamps encode as ISO strings. */\nexport const Readiness = Schema.Struct({\n domain: Schema.String,\n attachmentId: Schema.NullOr(Schema.String),\n overall: Storage.Overall,\n requirements: Schema.Array(\n Schema.Struct({\n operationId: Schema.NullOr(Plan.OperationId),\n record: DnsRecord.Model,\n status: Storage.RequirementStatus,\n evidence: Schema.Array(Verify.Evidence),\n }),\n ),\n host: Schema.Array(Verify.HostEvidence),\n checkedAt: Schema.DateTimeUtcFromString,\n nextCheckAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\nexport type Readiness = typeof Readiness.Type;\n\nconst Redirected = HttpApiSchema.WithHeaders(HttpApiSchema.Empty(302), {\n location: Schema.String,\n});\n\n// ---------------------------------------------------------------------------------------------\n// Errors: one wire body, the status from `DomainKit.Error.httpStatus`\n// ---------------------------------------------------------------------------------------------\n\n/** `DomainKit.Error` narrowed to the reasons that answer with `status`. */\nconst errorAt = (status: number) =>\n Errors.DomainKitError.check(\n Schema.makeFilter((error: Errors.DomainKitError) => error.httpStatus === status),\n ).pipe(HttpApiSchema.status(status));\n\nconst errors = [400, 401, 403, 404, 409, 500, 501, 502, 503].map(errorAt);\n\n// ---------------------------------------------------------------------------------------------\n// The group\n// ---------------------------------------------------------------------------------------------\n\nexport const group = HttpApiGroup.make(\"domainkit\")\n .add(\n HttpApiEndpoint.get(\"inspect\", \"/domains/:domain\", {\n params: { domain: Schema.String },\n success: Snapshot,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"discover\", \"/domains/:domain/discovery\", {\n params: { domain: Schema.String },\n success: Discovery,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"start\", \"/connections\", {\n payload: StartPayload,\n success: Started,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"callback\", \"/callback/:provider\", {\n params: { provider: Schema.String },\n // `Connect.complete` reads every callback parameter off the request URL, because a provider\n // may return `error`, `teamId`, or `configurationId` too. These two are declared so the\n // OpenAPI document names what a provider is expected to send back.\n query: { state: Schema.String, code: Schema.optionalKey(Schema.String) },\n success: Redirected,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"attach\", \"/connections/:connectionId/attachments\", {\n params: { connectionId: Schema.String },\n payload: AttachPayload,\n success: Started,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.delete(\"detach\", \"/attachments/:attachmentId\", {\n params: { attachmentId: Schema.String },\n success: Schema.Void,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.delete(\"disconnect\", \"/connections/:connectionId\", {\n params: { connectionId: Schema.String },\n success: Schema.Void,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"createPlan\", \"/domains/:domain/plans\", {\n params: { domain: Schema.String },\n payload: PlanPayload,\n success: Plan.Model,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"approve\", \"/plans/:planId/approvals\", {\n params: { planId: Plan.PlanId },\n payload: ApprovePayload,\n success: Approval.Model,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"reject\", \"/plans/:planId/rejections\", {\n params: { planId: Plan.PlanId },\n payload: RejectPayload,\n success: Attempt,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"apply\", \"/approvals/:approvalId/apply\", {\n params: { approvalId: Approval.ApprovalId },\n success: Receipt.Model,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"plan\", \"/plans/:planId\", {\n params: { planId: Plan.PlanId },\n success: Attempt,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"receipt\", \"/receipts/:receiptId\", {\n params: { receiptId: Receipt.ReceiptId },\n success: Receipt.Model,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"observe\", \"/domains/:domain/observations\", {\n params: { domain: Schema.String },\n payload: ObservePayload,\n success: Readiness,\n error: errors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"cleanupPlan\", \"/receipts/:receiptId/cleanup-plans\", {\n params: { receiptId: Receipt.ReceiptId },\n success: Plan.Model,\n error: errors,\n }),\n );\n// Cleanup approve, reject, and apply reuse those routes: the attempt knows its kind.\n\nexport type Group = typeof group;\n\n/** Every route in the group, by name; what `Identity.authorize` is asked about. */\nexport type EndpointName = HttpApiGroup.Endpoints<Group>[\"identifier\"];\n\nexport interface Options {\n /**\n * Where the callback route is reachable from the provider, without the `/callback/:provider`\n * suffix. Defaults to the incoming request's origin and mount path.\n */\n readonly callbackBaseUrl?: string;\n /** Where interactive flows return when the callback carries no `returnTo`. */\n readonly defaultReturnTo?: string;\n}\n\n/** Everything the handlers need: the lifecycle services, Storage, and the host's `Identity`. */\nexport type Services =\n | Provision.Service\n | Cleanup.Service\n | Connect.Service\n | Verify.Service\n | Providers.Service\n | Storage.Service\n | Identity;\n\n// ---------------------------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------------------------\n\nconst START_ROUTE = \"/connections\";\nconst callbackRoute = (provider: string) => `/callback/${encodeURIComponent(provider)}`;\n\nconst invalid = (message: string, field?: string) =>\n Errors.fail(new Reason.InvalidInput({ message, ...(field === undefined ? {} : { field }) }));\n\n/** The request as an absolute URL: the web original when there is one, else scheme plus `Host`. */\nconst absoluteUrl = (\n request: HttpServerRequest.HttpServerRequest,\n): Effect.Effect<URL, Errors.DomainKitError> =>\n Effect.suspend(() => {\n try {\n return Effect.succeed(new URL(request.originalUrl));\n } catch {\n const url = HttpServerRequest.toURL(request);\n return Option.isNone(url)\n ? invalid(\"The request has no usable origin; set callbackBaseUrl\", \"callbackBaseUrl\")\n : Effect.succeed(url.value);\n }\n });\n\n/**\n * The absolute URL the provider redirects back to. `callbackBaseUrl` wins when the host set it,\n * because a proxy that rewrites `Host` leaves the request pointing at an origin the browser never\n * sees; otherwise it follows the prefix the group is mounted at, derived by stripping the handling\n * route's own path off the request.\n */\nconst callbackUrlFor = (input: {\n readonly request: HttpServerRequest.HttpServerRequest;\n readonly provider: string;\n readonly options: Options;\n /** The path of the route serving this request, stripped to find the mount. */\n readonly route: string;\n}): Effect.Effect<URL, Errors.DomainKitError> =>\n Effect.suspend(() => {\n const suffix = `/callback/${encodeURIComponent(input.provider)}`;\n const configured = input.options.callbackBaseUrl;\n if (configured !== undefined) {\n return Effect.try({\n try: () => new URL(`${configured.replace(/\\/+$/, \"\")}${suffix}`),\n catch: () => callbackConfigurationError(`${configured} is not a URL`),\n });\n }\n return Effect.flatMap(absoluteUrl(input.request), (url) => {\n const path = url.pathname;\n if (!path.endsWith(input.route)) {\n return invalid(\n `The ${input.route} route is not mounted where it says; set callbackBaseUrl`,\n \"callbackBaseUrl\",\n );\n }\n return Effect.succeed(\n new URL(`${url.origin}${path.slice(0, path.length - input.route.length)}${suffix}`),\n );\n });\n });\n\nconst callbackConfigurationError = (message: string) =>\n new Errors.DomainKitError({\n reason: new Reason.InvalidInput({ message, field: \"callbackBaseUrl\" }),\n });\n\n/**\n * Where the callback may send the customer: a path under the callback's own base, or an absolute\n * URL on its origin. A destination that leaves the application is an open redirect, whoever\n * supplied it.\n */\nconst sameOrigin = (destination: string, callback: URL): string | null => {\n try {\n // Resolving against the callback is what makes this safe: the URL parser normalizes the forms\n // a browser would follow off-origin (`//host`, `/\\host`, `\\/host`, encoded hosts) into a real\n // origin, so comparing origins catches every one of them.\n const url = new URL(destination, callback);\n return url.origin === callback.origin ? url.toString() : null;\n } catch {\n return null;\n }\n};\n\nconst snapshotOf = (snapshot: Connect.Snapshot): Snapshot => ({\n domain: snapshot.domain,\n attachmentId: snapshot.attachment?.id ?? null,\n connectionId: snapshot.connection?.id ?? null,\n provider: snapshot.authorization?.provider ?? null,\n method: snapshot.authorization?.method ?? null,\n status:\n snapshot.connection === null\n ? \"disconnected\"\n : snapshot.authorization?.revocation === \"active\"\n ? \"connected\"\n : \"reconnect\",\n lastReceiptId: snapshot.lastReceiptId,\n reusable: snapshot.reusable.map(({ connection, provider, method }) => ({\n connectionId: connection.id,\n provider,\n method,\n })),\n providers: snapshot.providers.map(({ id, name, methods }) => ({ id, name, methods })),\n});\n\n/** The wire method as `Connect` takes it; interactive cases carry the caller's return destination. */\nconst methodOf = (method: Method): Connect.Method => {\n switch (method._tag) {\n case \"Token\":\n return Connect.Method.token(method.values);\n case \"OAuth\":\n return Connect.Method.oauth(\n method.returnTo === undefined ? {} : { returnTo: method.returnTo },\n );\n case \"Integration\":\n return Connect.Method.integration(\n method.returnTo === undefined ? {} : { returnTo: method.returnTo },\n );\n }\n};\n\nconst candidatesOf = (\n candidates: ReadonlyArray<{ readonly zone: string; readonly label: string }>,\n): ReadonlyArray<Candidate> => candidates.map(({ zone, label }) => new Candidate({ zone, label }));\n\n/**\n * Handlers for `group` inside the host's API. Every handler derives `Principal` from `Identity`\n * for the request it is serving and provides it to the lifecycle services.\n */\nexport const layer = <ApiId extends string, Groups extends HttpApiGroup.Constraint>(\n api: HttpApi.HttpApi<ApiId, Groups>,\n options: Options = {},\n): Layer.Layer<HttpApiGroup.Service<ApiId, \"domainkit\">, never, Services> =>\n // The host's API carries its own groups beside this one; only `\"domainkit\"` is implemented here,\n // and `HttpApiBuilder.group` needs the group's own endpoint types to check the handlers.\n HttpApiBuilder.group(api as unknown as HttpApi.HttpApi<ApiId, Group>, \"domainkit\", (handlers) =>\n Effect.gen(function* () {\n const identity = yield* Identity;\n const connect = yield* Connect.Service;\n const provision = yield* Provision.Service;\n const cleanup = yield* Cleanup.Service;\n const verify = yield* Verify.Service;\n const storage = yield* Storage.Service;\n\n /**\n * Run a lifecycle effect as the principal the host derives from this request, once the host\n * has allowed that principal onto this route.\n */\n const as = <A>(\n endpoint: EndpointName,\n request: HttpServerRequest.HttpServerRequest,\n effect: Effect.Effect<A, Errors.DomainKitError, Principal.Service>,\n ): Effect.Effect<A, Errors.DomainKitError> =>\n Effect.flatMap(identity.principal(request), (principal) =>\n Effect.flatMap(identity.authorize?.(principal, endpoint) ?? Effect.void, () =>\n Effect.provideService(effect, Principal.Service, principal),\n ),\n );\n\n const snapshot = (domain: string) => Effect.map(connect.inspect(domain), snapshotOf);\n\n const discovered = (discovery: Connect.Discovery): Discovery => {\n switch (discovery._tag) {\n case \"Resolved\":\n return new DiscoveryResolved({\n connectionId: discovery.connectionId,\n zone: discovery.target.zone,\n label: discovery.target.label,\n });\n case \"SelectionRequired\":\n return new DiscoverySelectionRequired({\n candidates: discovery.candidates.map(({ connectionId, target }) => ({\n connectionId,\n zone: target.zone,\n label: target.label,\n })),\n });\n case \"NotFound\":\n return new DiscoveryNotFound({ nameservers: discovery.nameservers });\n }\n };\n\n const connected = (domain: string) =>\n Effect.map(snapshot(domain), (value) => new Connected({ snapshot: value }));\n\n const startedOf = (\n started: Connect.Started,\n domain: string,\n ): Effect.Effect<Started, Errors.DomainKitError, Principal.Service> => {\n switch (started._tag) {\n case \"Connected\":\n return connected(domain);\n case \"Redirect\":\n return Effect.succeed(new Redirect({ authorizationUrl: started.authorizationUrl }));\n case \"SelectionRequired\":\n return Effect.succeed(\n new SelectionRequired({\n connectionId: started.connection.id,\n candidates: candidatesOf(started.candidates),\n }),\n );\n }\n };\n\n /**\n * Attach with a zone the client picked out of a `SelectionRequired`. The provider target\n * behind a zone never crosses the wire, so resolve the candidates again and match by zone.\n */\n const attachAt = (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string | undefined;\n }): Effect.Effect<Started, Errors.DomainKitError, Principal.Service> =>\n Effect.gen(function* () {\n const first = yield* connect.attach({\n connectionId: input.connectionId,\n domain: input.domain,\n });\n if (!(\"_tag\" in first)) return yield* connected(input.domain);\n if (input.zone === undefined) {\n return new SelectionRequired({\n connectionId: input.connectionId,\n candidates: candidatesOf(first.candidates),\n });\n }\n const target = first.candidates.find(({ zone }) => zone === input.zone);\n if (target === undefined) {\n return yield* Errors.fail(new Reason.NotFound({ entity: \"zone\", id: input.zone }));\n }\n yield* connect.attach({\n connectionId: input.connectionId,\n domain: input.domain,\n target,\n });\n return yield* connected(input.domain);\n });\n\n /** Provisioning and cleanup share the approve and apply routes; the attempt knows its kind. */\n const kindOf = (attempt: Storage.Attempt) =>\n attempt.kind === \"cleanup\" ? cleanup : provision;\n\n return handlers\n .handle(\"inspect\", ({ params, request }) => as(\"inspect\", request, snapshot(params.domain)))\n .handle(\"discover\", ({ params, request }) =>\n as(\"discover\", request, Effect.map(connect.discover(params.domain), discovered)),\n )\n .handle(\"start\", ({ payload, request }) =>\n as(\n \"start\",\n request,\n Effect.gen(function* () {\n // Token methods connect in one call; the interactive ones need somewhere to land.\n const callbackUrl =\n payload.method._tag === \"Token\"\n ? undefined\n : (yield* callbackUrlFor({\n request,\n provider: payload.provider,\n options,\n route: START_ROUTE,\n })).toString();\n const started = yield* connect.start({\n provider: payload.provider,\n domain: payload.domain,\n method: methodOf(payload.method),\n ...(callbackUrl === undefined ? {} : { callbackUrl }),\n });\n return yield* startedOf(started, payload.domain);\n }),\n ),\n )\n .handle(\"callback\", ({ params, query, request }) =>\n as(\n \"callback\",\n request,\n Effect.gen(function* () {\n const url = yield* absoluteUrl(request);\n // Resolve the destination against the callback's public base, not the request: a\n // proxy that rewrites `Host` leaves the request on an origin the browser never sees.\n const base = yield* callbackUrlFor({\n request,\n provider: params.provider,\n options,\n route: callbackRoute(params.provider),\n });\n // Where the customer lands comes from the continuation this owner started, never\n // from the provider's query string, and it is resolved before the callback is spent:\n // a server with nowhere to send them must not connect the provider and then fail.\n const continuation = yield* storage.continuations.get(query.state);\n const requested = continuation.returnTo ?? options.defaultReturnTo;\n if (requested === undefined) {\n return yield* invalid(\n \"The flow carried no returnTo and the server has no defaultReturnTo\",\n \"returnTo\",\n );\n }\n const destination = sameOrigin(requested, base);\n if (destination === null) {\n return yield* invalid(`${requested} leaves this application`, \"returnTo\");\n }\n yield* connect.complete({\n continuationId: query.state,\n callbackUrl: url.toString(),\n });\n return HttpApiSchema.withHeaders({\n body: undefined as void,\n headers: { location: destination },\n });\n }),\n ),\n )\n .handle(\"attach\", ({ params, payload, request }) =>\n as(\n \"attach\",\n request,\n attachAt({\n connectionId: params.connectionId,\n domain: payload.domain,\n zone: payload.zone,\n }),\n ),\n )\n .handle(\"detach\", ({ params, request }) =>\n as(\"detach\", request, connect.detach(params.attachmentId)),\n )\n .handle(\"disconnect\", ({ params, request }) =>\n as(\"disconnect\", request, connect.disconnect(params.connectionId)),\n )\n .handle(\"createPlan\", ({ params, payload, request }) =>\n as(\n \"createPlan\",\n request,\n provision.plan({ domain: params.domain, requirements: payload.requirements }),\n ),\n )\n .handle(\"approve\", ({ params, payload, request }) =>\n as(\n \"approve\",\n request,\n Effect.gen(function* () {\n const attempt = yield* storage.attempts.get(params.planId);\n return yield* kindOf(attempt).approve(params.planId, {\n ...(payload.operationIds === undefined\n ? {}\n : { operationIds: payload.operationIds, allowPartial: true }),\n });\n }),\n ),\n )\n .handle(\"reject\", ({ params, payload, request }) =>\n as(\n \"reject\",\n request,\n Effect.gen(function* () {\n const attempt = yield* storage.attempts.get(params.planId);\n return yield* kindOf(attempt).reject(params.planId, {\n ...(payload.reason === undefined ? {} : { reason: payload.reason }),\n });\n }),\n ),\n )\n .handle(\"apply\", ({ params, request }) =>\n as(\n \"apply\",\n request,\n Effect.gen(function* () {\n const attempt = yield* storage.attempts.byApproval(params.approvalId);\n return yield* kindOf(attempt).apply(params.approvalId);\n }),\n ),\n )\n .handle(\"plan\", ({ params, request }) =>\n as(\n \"plan\",\n request,\n Effect.map(storage.attempts.get(params.planId), (attempt) => ({\n plan: attempt.plan,\n status: attempt.status,\n approval: attempt.approval,\n receipt: attempt.receipt,\n rejection: attempt.rejection,\n })),\n ),\n )\n .handle(\"receipt\", ({ params, request }) =>\n as(\n \"receipt\",\n request,\n Effect.flatMap(storage.attempts.byReceipt(params.receiptId), (attempt) =>\n attempt.receipt === null\n ? Errors.fail(new Reason.NotFound({ entity: \"receipt\", id: params.receiptId }))\n : Effect.succeed(attempt.receipt),\n ),\n ),\n )\n .handle(\"observe\", ({ params, payload, request }) =>\n as(\n \"observe\",\n request,\n verify.observe({\n domain: params.domain,\n ...(payload.requirements === undefined ? {} : { requirements: payload.requirements }),\n }),\n ),\n )\n .handle(\"cleanupPlan\", ({ params, request }) =>\n as(\"cleanupPlan\", request, cleanup.plan({ receiptId: params.receiptId })),\n );\n }),\n ) as Layer.Layer<HttpApiGroup.Service<ApiId, \"domainkit\">, never, Services>;\n\n/** A standalone API for hosts not on HttpApi. Mount at any prefix. */\nexport const api: HttpApi.HttpApi<\"domainkit\", Group> = HttpApi.make(\"domainkit\").add(group);\n\nexport interface WebHandlerOptions extends Options {\n /** Mount every route under this path, e.g. `/api/domainkit`. */\n readonly prefix?: `/${string}`;\n}\n\n/** The Promise edge: a `fetch`-shaped handler over the group for hosts that are not Effect-native. */\nexport const toWebHandler = (\n services: Layer.Layer<Services, Errors.DomainKitError>,\n options: WebHandlerOptions = {},\n): {\n readonly handler: (request: Request) => Promise<Response>;\n readonly dispose: () => Promise<void>;\n} => {\n // `group.prefix` widens the endpoint paths in the type, which `Group` states unprefixed; the\n // handlers are keyed by endpoint identifier, so the routes still line up.\n const prefixed =\n options.prefix === undefined\n ? api\n : (HttpApi.make(\"domainkit\").add(group.prefix(options.prefix)) as unknown as HttpApi.HttpApi<\n \"domainkit\",\n Group\n >);\n const app = HttpApiBuilder.layer(prefixed).pipe(\n Layer.provide(layer(prefixed, options)),\n Layer.provide(services),\n Layer.provide(HttpServer.layerServices),\n );\n return HttpRouter.toWebHandler(app, { disableLogger: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAa,WAAb,cAA8B,QAAQ,QAAmC,CAAC,CACxE,4BACF,CAAC,CAAC,CAAC;AAMH,MAAa,mBAAmB,OAAO,SAAS;CAAC;CAAgB;CAAa;AAAW,CAAC;;AAI1F,MAAa,QAAQ,OAAO,OAAO;CACjC,MAAM,OAAO;CACb,UAAU,OAAO;CACjB,QA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AM,QAAQ,QAAQ,GACtB,MAAM,QAAQ,WAAW,aAAa,CACxC;CACA,OAAO,WAAW,aAAa,KAAK,EAAE,eAAe,KAAK,CAAC;AAC7D"}
|
package/dist/Storage.mjs
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { __exportAll } from "./_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { Model } from "./DnsRecord.mjs";
|
|
3
|
+
import { Kind, Model as Model$1, OperationId, PlanId } from "./Plan.mjs";
|
|
4
|
+
import { Busy, StorageFailed } from "./Reason.mjs";
|
|
5
|
+
import { DomainKitError, fail, isDomainKitError } from "./internal/error.mjs";
|
|
6
|
+
import { Model as Model$2 } from "./Approval.mjs";
|
|
7
|
+
import { Service as Service$1 } from "./Principal.mjs";
|
|
8
|
+
import { makeMemory } from "./internal/storage-memory.mjs";
|
|
9
|
+
import { Model as Model$3, ReceiptId } from "./Receipt.mjs";
|
|
10
|
+
import { Context, Effect, Layer, Option, Schema } from "effect";
|
|
11
|
+
//#region src/Storage.ts
|
|
12
|
+
/**
|
|
13
|
+
* Everything DomainKit persists, behind one service the host installs once. Every method requires
|
|
14
|
+
* `Principal` and is scoped by it. `@domainkit/capsuledb` ships the Postgres implementation;
|
|
15
|
+
* `domainkit/testing` ships the memory one; both pass `Testing.conformance.storage`.
|
|
16
|
+
*
|
|
17
|
+
* Storage never sees plaintext credentials: `Connect` seals secrets through `Custody` before
|
|
18
|
+
* writing a `Credential` row and opens them after reading one.
|
|
19
|
+
*
|
|
20
|
+
* Grouped by noun so the 25-odd methods stay navigable. Implementations must satisfy the
|
|
21
|
+
* invariants documented per group; the conformance suite checks them.
|
|
22
|
+
*/
|
|
23
|
+
var Storage_exports = /* @__PURE__ */ __exportAll({
|
|
24
|
+
Attachment: () => Attachment,
|
|
25
|
+
Attempt: () => Attempt,
|
|
26
|
+
AttemptStatus: () => AttemptStatus,
|
|
27
|
+
AuthMethod: () => AuthMethod,
|
|
28
|
+
Authorization: () => Authorization,
|
|
29
|
+
Capability: () => Capability,
|
|
30
|
+
Connection: () => Connection,
|
|
31
|
+
Continuation: () => Continuation,
|
|
32
|
+
Credential: () => Credential,
|
|
33
|
+
Overall: () => Overall,
|
|
34
|
+
Readiness: () => Readiness,
|
|
35
|
+
Rejection: () => Rejection,
|
|
36
|
+
RequirementStatus: () => RequirementStatus,
|
|
37
|
+
Service: () => Service,
|
|
38
|
+
fromAsync: () => fromAsync,
|
|
39
|
+
layerFromAsync: () => layerFromAsync,
|
|
40
|
+
layerMemory: () => layerMemory,
|
|
41
|
+
layerMemoryWith: () => layerMemoryWith,
|
|
42
|
+
makeMemory: () => makeMemory
|
|
43
|
+
});
|
|
44
|
+
const Capability = Schema.Literals(["dns:read", "dns:write"]);
|
|
45
|
+
const AuthMethod = Schema.Literals([
|
|
46
|
+
"token",
|
|
47
|
+
"oauth",
|
|
48
|
+
"integration"
|
|
49
|
+
]);
|
|
50
|
+
/** Sealed provider credential plus the metadata needed without unsealing it. */
|
|
51
|
+
var Credential = class extends Schema.Class("@domainkit/Storage/Credential")({
|
|
52
|
+
ciphertext: Schema.String,
|
|
53
|
+
expiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
|
54
|
+
rotatedAt: Schema.DateTimeUtcFromString
|
|
55
|
+
}) {};
|
|
56
|
+
/** One provider authorization (an OAuth grant or a token) owned by a principal. */
|
|
57
|
+
var Authorization = class extends Schema.Class("@domainkit/Storage/Authorization")({
|
|
58
|
+
id: Schema.String,
|
|
59
|
+
ownerId: Schema.String,
|
|
60
|
+
provider: Schema.String,
|
|
61
|
+
method: AuthMethod,
|
|
62
|
+
capabilities: Schema.Array(Capability),
|
|
63
|
+
/** Provider-specific account context (account id, team id, ...) decoded by the provider's `context` schema. */
|
|
64
|
+
context: Schema.Unknown,
|
|
65
|
+
revocation: Schema.Literals([
|
|
66
|
+
"active",
|
|
67
|
+
"pending",
|
|
68
|
+
"revoked"
|
|
69
|
+
]),
|
|
70
|
+
createdBy: Schema.String,
|
|
71
|
+
createdAt: Schema.DateTimeUtcFromString
|
|
72
|
+
}) {};
|
|
73
|
+
/** A connection is the principal-facing handle over an authorization; one authorization, many domains. */
|
|
74
|
+
var Connection = class extends Schema.Class("@domainkit/Storage/Connection")({
|
|
75
|
+
id: Schema.String,
|
|
76
|
+
ownerId: Schema.String,
|
|
77
|
+
authorizationId: Schema.String,
|
|
78
|
+
createdAt: Schema.DateTimeUtcFromString
|
|
79
|
+
}) {};
|
|
80
|
+
var Attachment = class extends Schema.Class("@domainkit/Storage/Attachment")({
|
|
81
|
+
id: Schema.String,
|
|
82
|
+
ownerId: Schema.String,
|
|
83
|
+
connectionId: Schema.String,
|
|
84
|
+
domain: Schema.String,
|
|
85
|
+
zone: Schema.String,
|
|
86
|
+
/** Provider zone identity (zone id, account id) decoded by the provider's `context` schema. */
|
|
87
|
+
target: Schema.Unknown,
|
|
88
|
+
createdAt: Schema.DateTimeUtcFromString
|
|
89
|
+
}) {};
|
|
90
|
+
/** Interactive-flow state between `Connect.start` and `Connect.complete`. */
|
|
91
|
+
var Continuation = class extends Schema.Class("@domainkit/Storage/Continuation")({
|
|
92
|
+
id: Schema.String,
|
|
93
|
+
ownerId: Schema.String,
|
|
94
|
+
actorId: Schema.String,
|
|
95
|
+
provider: Schema.String,
|
|
96
|
+
payload: Schema.Unknown,
|
|
97
|
+
returnTo: Schema.NullOr(Schema.String),
|
|
98
|
+
expiresAt: Schema.DateTimeUtcFromString
|
|
99
|
+
}) {};
|
|
100
|
+
const AttemptStatus = Schema.Literals([
|
|
101
|
+
"planned",
|
|
102
|
+
"approved",
|
|
103
|
+
"applying",
|
|
104
|
+
"complete",
|
|
105
|
+
"partial",
|
|
106
|
+
"failed",
|
|
107
|
+
"expired",
|
|
108
|
+
"rejected"
|
|
109
|
+
]);
|
|
110
|
+
/** Who declined the plan, why, and when. Terminal: the domain needs a new plan. */
|
|
111
|
+
const Rejection = Schema.Struct({
|
|
112
|
+
actorId: Schema.String,
|
|
113
|
+
reason: Schema.NullOr(Schema.String),
|
|
114
|
+
at: Schema.DateTimeUtcFromString
|
|
115
|
+
});
|
|
116
|
+
/** One durable plan -> approval -> receipt lifecycle. */
|
|
117
|
+
var Attempt = class extends Schema.Class("@domainkit/Storage/Attempt")({
|
|
118
|
+
id: PlanId,
|
|
119
|
+
ownerId: Schema.String,
|
|
120
|
+
attachmentId: Schema.String,
|
|
121
|
+
kind: Kind,
|
|
122
|
+
status: AttemptStatus,
|
|
123
|
+
plan: Model$1,
|
|
124
|
+
approval: Schema.NullOr(Model$2),
|
|
125
|
+
receipt: Schema.NullOr(Model$3),
|
|
126
|
+
rejection: Schema.NullOr(Rejection),
|
|
127
|
+
/** Cleanup attempts point at the provisioning receipt they undo. */
|
|
128
|
+
sourceReceiptId: Schema.NullOr(ReceiptId),
|
|
129
|
+
leaseExpiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
|
130
|
+
/** Why the last apply stopped before any write; cleared on the next claim. */
|
|
131
|
+
failure: Schema.NullOr(Schema.String),
|
|
132
|
+
updatedAt: Schema.DateTimeUtcFromString
|
|
133
|
+
}) {};
|
|
134
|
+
const RequirementStatus = Schema.Literals([
|
|
135
|
+
"satisfied",
|
|
136
|
+
"missing",
|
|
137
|
+
"mismatch",
|
|
138
|
+
"unknown"
|
|
139
|
+
]);
|
|
140
|
+
const Overall = Schema.Literals([
|
|
141
|
+
"ready",
|
|
142
|
+
"pending",
|
|
143
|
+
"failed"
|
|
144
|
+
]);
|
|
145
|
+
/**
|
|
146
|
+
* Latest observed readiness for one domain, written by `Verify.observe`. Keyed by domain so
|
|
147
|
+
* observe-only hosts (no attachment, public DNS alone) get the same row; `attachmentId` links the
|
|
148
|
+
* attachment when one exists.
|
|
149
|
+
*/
|
|
150
|
+
var Readiness = class extends Schema.Class("@domainkit/Storage/Readiness")({
|
|
151
|
+
domain: Schema.String,
|
|
152
|
+
attachmentId: Schema.NullOr(Schema.String),
|
|
153
|
+
ownerId: Schema.String,
|
|
154
|
+
overall: Overall,
|
|
155
|
+
requirements: Schema.Array(Schema.Struct({
|
|
156
|
+
operationId: Schema.NullOr(OperationId),
|
|
157
|
+
record: Model,
|
|
158
|
+
status: RequirementStatus,
|
|
159
|
+
/** Encoded `Verify.Evidence` values. */
|
|
160
|
+
evidence: Schema.Array(Schema.Unknown)
|
|
161
|
+
})),
|
|
162
|
+
/** Encoded `Verify.HostEvidence` values, keyed by `source` on merge. */
|
|
163
|
+
host: Schema.Array(Schema.Unknown),
|
|
164
|
+
/** When the current pending streak began; drives the backoff ladder. */
|
|
165
|
+
pendingSince: Schema.NullOr(Schema.DateTimeUtcFromString),
|
|
166
|
+
checkedAt: Schema.DateTimeUtcFromString,
|
|
167
|
+
nextCheckAt: Schema.NullOr(Schema.DateTimeUtcFromString)
|
|
168
|
+
}) {};
|
|
169
|
+
var Service = class extends Context.Service()("@domainkit/Storage") {};
|
|
170
|
+
/** In-memory implementation for tests and local development. Not for production. */
|
|
171
|
+
const layerMemory = Layer.sync(Service)(() => makeMemory());
|
|
172
|
+
/** `layerMemory` with fault injection for storage-failure tests. */
|
|
173
|
+
const layerMemoryWith = (options) => Layer.sync(Service)(() => makeMemory(options));
|
|
174
|
+
const storageFailed = (operation) => (cause) => isDomainKitError(cause) ? cause : new DomainKitError({ reason: new StorageFailed({
|
|
175
|
+
operation,
|
|
176
|
+
message: cause instanceof Error ? cause.message : String(cause)
|
|
177
|
+
}) });
|
|
178
|
+
/** Wraps a Promise-shaped implementation. Rejections become `StorageFailed`. */
|
|
179
|
+
const fromAsync = (service) => {
|
|
180
|
+
const call = (operation, run) => Effect.flatMap(Service$1, (principal) => Effect.tryPromise({
|
|
181
|
+
try: () => run(principal),
|
|
182
|
+
catch: storageFailed(operation)
|
|
183
|
+
}));
|
|
184
|
+
const option = (operation, run) => call(operation, run).pipe(Effect.map(Option.fromNullishOr));
|
|
185
|
+
return {
|
|
186
|
+
authorizations: {
|
|
187
|
+
upsert: (input) => call("authorizations.upsert", (p) => service.authorizations.upsert(p, input)),
|
|
188
|
+
get: (id) => call("authorizations.get", (p) => service.authorizations.get(p, id)),
|
|
189
|
+
credential: (id) => call("authorizations.credential", (p) => service.authorizations.credential(p, id)),
|
|
190
|
+
rotate: (id, credential) => call("authorizations.rotate", (p) => service.authorizations.rotate(p, id, credential)),
|
|
191
|
+
promoteCapabilities: (id, capabilities) => call("authorizations.promoteCapabilities", (p) => service.authorizations.promoteCapabilities(p, id, capabilities)),
|
|
192
|
+
revoke: (id, revoke) => call("authorizations.prepareRevocation", (p) => service.authorizations.prepareRevocation(p, id)).pipe(Effect.flatMap(() => revoke), Effect.flatMap(() => call("authorizations.completeRevocation", (p) => service.authorizations.completeRevocation(p, id)))),
|
|
193
|
+
recoverRevocations: (revoke) => call("authorizations.pendingRevocations", (p) => service.authorizations.pendingRevocations(p)).pipe(Effect.flatMap((pending) => Effect.forEach(pending, (authorization) => revoke(authorization).pipe(Effect.flatMap(() => call("authorizations.completeRevocation", (p) => service.authorizations.completeRevocation(p, authorization.id)))))), Effect.map((completed) => completed.length))
|
|
194
|
+
},
|
|
195
|
+
connections: {
|
|
196
|
+
create: (authorizationId) => call("connections.create", (p) => service.connections.create(p, authorizationId)),
|
|
197
|
+
get: (id) => call("connections.get", (p) => service.connections.get(p, id)),
|
|
198
|
+
list: (filter) => call("connections.list", (p) => service.connections.list(p, filter)),
|
|
199
|
+
remove: (id) => call("connections.remove", (p) => service.connections.remove(p, id))
|
|
200
|
+
},
|
|
201
|
+
attachments: {
|
|
202
|
+
create: (input) => call("attachments.create", (p) => service.attachments.create(p, input)),
|
|
203
|
+
get: (id) => call("attachments.get", (p) => service.attachments.get(p, id)),
|
|
204
|
+
byDomain: (domain) => option("attachments.byDomain", (p) => service.attachments.byDomain(p, domain)),
|
|
205
|
+
list: (connectionId) => call("attachments.list", (p) => service.attachments.list(p, connectionId)),
|
|
206
|
+
remove: (id) => call("attachments.remove", (p) => service.attachments.remove(p, id))
|
|
207
|
+
},
|
|
208
|
+
continuations: {
|
|
209
|
+
put: (continuation) => call("continuations.put", (p) => service.continuations.put(p, continuation)),
|
|
210
|
+
get: (id) => call("continuations.get", (p) => service.continuations.get(p, id)),
|
|
211
|
+
consume: (id) => call("continuations.consume", (p) => service.continuations.consume(p, id))
|
|
212
|
+
},
|
|
213
|
+
attempts: {
|
|
214
|
+
create: (attempt) => call("attempts.create", (p) => service.attempts.create(p, attempt)),
|
|
215
|
+
get: (id) => call("attempts.get", (p) => service.attempts.get(p, id)),
|
|
216
|
+
byApproval: (id) => call("attempts.byApproval", (p) => service.attempts.byApproval(p, id)),
|
|
217
|
+
byReceipt: (id) => call("attempts.byReceipt", (p) => service.attempts.byReceipt(p, id)),
|
|
218
|
+
latest: (attachmentId, kind) => option("attempts.latest", (p) => service.attempts.latest(p, attachmentId, kind)),
|
|
219
|
+
approve: (id, approval) => call("attempts.approve", (p) => service.attempts.approve(p, id, approval)),
|
|
220
|
+
reject: (id, input) => call("attempts.reject", (p) => service.attempts.reject(p, id, input)),
|
|
221
|
+
claim: (id, lease) => call("attempts.claim", (p) => service.attempts.claim(p, id, lease)),
|
|
222
|
+
complete: (id, receipt) => call("attempts.complete", (p) => service.attempts.complete(p, id, receipt)),
|
|
223
|
+
fail: (id, message) => call("attempts.fail", (p) => service.attempts.fail(p, id, message))
|
|
224
|
+
},
|
|
225
|
+
readiness: {
|
|
226
|
+
put: (readiness) => call("readiness.put", (p) => service.readiness.put(p, readiness)),
|
|
227
|
+
get: (domain) => option("readiness.get", (p) => service.readiness.get(p, domain))
|
|
228
|
+
},
|
|
229
|
+
withLock: (key, effect) => Effect.acquireRelease(call("acquireLock", (p) => service.acquireLock(p, key)).pipe(Effect.flatMap((acquired) => acquired ? Effect.void : fail(new Busy({ key })))), () => call("releaseLock", (p) => service.releaseLock(p, key)).pipe(Effect.ignore)).pipe(Effect.flatMap(() => effect), Effect.scoped)
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
const layerFromAsync = (service) => Layer.succeed(Service)(fromAsync(service));
|
|
233
|
+
//#endregion
|
|
234
|
+
export { Attachment, Attempt, AttemptStatus, AuthMethod, Authorization, Capability, Connection, Continuation, Credential, Overall, Readiness, Rejection, RequirementStatus, Service, Storage_exports, fromAsync, layerFromAsync, layerMemory, layerMemoryWith, makeMemory };
|
|
235
|
+
|
|
236
|
+
//# sourceMappingURL=Storage.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Storage.mjs","names":["Plan.PlanId","Plan.Kind","Plan.Model","Approval.Model","Receipt.Model","Receipt.ReceiptId","Plan.OperationId","DnsRecord.Model","Errors.isDomainKitError","Errors.DomainKitError","Reason.StorageFailed","Principal.Service","Errors.fail","Reason.Busy"],"sources":["../src/Storage.ts"],"sourcesContent":["/**\n * Everything DomainKit persists, behind one service the host installs once. Every method requires\n * `Principal` and is scoped by it. `@domainkit/capsuledb` ships the Postgres implementation;\n * `domainkit/testing` ships the memory one; both pass `Testing.conformance.storage`.\n *\n * Storage never sees plaintext credentials: `Connect` seals secrets through `Custody` before\n * writing a `Credential` row and opens them after reading one.\n *\n * Grouped by noun so the 25-odd methods stay navigable. Implementations must satisfy the\n * invariants documented per group; the conformance suite checks them.\n */\nimport { Context, DateTime, Effect, Layer, Option, Schema } from \"effect\";\n\nimport * as Approval from \"./Approval.ts\";\nimport * as DnsRecord from \"./DnsRecord.ts\";\nimport * as Errors from \"./internal/error.ts\";\nimport * as Reason from \"./Reason.ts\";\nimport { makeMemory } from \"./internal/storage-memory.ts\";\nimport * as Plan from \"./Plan.ts\";\nimport * as Principal from \"./Principal.ts\";\nimport * as Receipt from \"./Receipt.ts\";\n\nexport type Fx<A> = Effect.Effect<A, Errors.DomainKitError, Principal.Service>;\n\n// ---------------------------------------------------------------------------------------------\n// Rows\n// ---------------------------------------------------------------------------------------------\n\nexport const Capability = Schema.Literals([\"dns:read\", \"dns:write\"]);\nexport type Capability = typeof Capability.Type;\n\nexport const AuthMethod = Schema.Literals([\"token\", \"oauth\", \"integration\"]);\nexport type AuthMethod = typeof AuthMethod.Type;\n\n/** Sealed provider credential plus the metadata needed without unsealing it. */\nexport class Credential extends Schema.Class<Credential>(\"@domainkit/Storage/Credential\")({\n ciphertext: Schema.String,\n expiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n rotatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** One provider authorization (an OAuth grant or a token) owned by a principal. */\nexport class Authorization extends Schema.Class<Authorization>(\"@domainkit/Storage/Authorization\")({\n id: Schema.String,\n ownerId: Schema.String,\n provider: Schema.String,\n method: AuthMethod,\n capabilities: Schema.Array(Capability),\n /** Provider-specific account context (account id, team id, ...) decoded by the provider's `context` schema. */\n context: Schema.Unknown,\n revocation: Schema.Literals([\"active\", \"pending\", \"revoked\"]),\n createdBy: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** A connection is the principal-facing handle over an authorization; one authorization, many domains. */\nexport class Connection extends Schema.Class<Connection>(\"@domainkit/Storage/Connection\")({\n id: Schema.String,\n ownerId: Schema.String,\n authorizationId: Schema.String,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport class Attachment extends Schema.Class<Attachment>(\"@domainkit/Storage/Attachment\")({\n id: Schema.String,\n ownerId: Schema.String,\n connectionId: Schema.String,\n domain: Schema.String,\n zone: Schema.String,\n /** Provider zone identity (zone id, account id) decoded by the provider's `context` schema. */\n target: Schema.Unknown,\n createdAt: Schema.DateTimeUtcFromString,\n}) {}\n\n/** Interactive-flow state between `Connect.start` and `Connect.complete`. */\nexport class Continuation extends Schema.Class<Continuation>(\"@domainkit/Storage/Continuation\")({\n id: Schema.String,\n ownerId: Schema.String,\n actorId: Schema.String,\n provider: Schema.String,\n payload: Schema.Unknown,\n returnTo: Schema.NullOr(Schema.String),\n expiresAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const AttemptStatus = Schema.Literals([\n \"planned\",\n \"approved\",\n \"applying\",\n \"complete\",\n \"partial\",\n \"failed\",\n \"expired\",\n \"rejected\",\n]);\nexport type AttemptStatus = typeof AttemptStatus.Type;\n\n/** Who declined the plan, why, and when. Terminal: the domain needs a new plan. */\nexport const Rejection = Schema.Struct({\n actorId: Schema.String,\n reason: Schema.NullOr(Schema.String),\n at: Schema.DateTimeUtcFromString,\n});\nexport type Rejection = typeof Rejection.Type;\n\n/** One durable plan -> approval -> receipt lifecycle. */\nexport class Attempt extends Schema.Class<Attempt>(\"@domainkit/Storage/Attempt\")({\n id: Plan.PlanId,\n ownerId: Schema.String,\n attachmentId: Schema.String,\n kind: Plan.Kind,\n status: AttemptStatus,\n plan: Plan.Model,\n approval: Schema.NullOr(Approval.Model),\n receipt: Schema.NullOr(Receipt.Model),\n rejection: Schema.NullOr(Rejection),\n /** Cleanup attempts point at the provisioning receipt they undo. */\n sourceReceiptId: Schema.NullOr(Receipt.ReceiptId),\n leaseExpiresAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n /** Why the last apply stopped before any write; cleared on the next claim. */\n failure: Schema.NullOr(Schema.String),\n updatedAt: Schema.DateTimeUtcFromString,\n}) {}\n\nexport const RequirementStatus = Schema.Literals([\"satisfied\", \"missing\", \"mismatch\", \"unknown\"]);\nexport type RequirementStatus = typeof RequirementStatus.Type;\n\nexport const Overall = Schema.Literals([\"ready\", \"pending\", \"failed\"]);\nexport type Overall = typeof Overall.Type;\n\n/**\n * Latest observed readiness for one domain, written by `Verify.observe`. Keyed by domain so\n * observe-only hosts (no attachment, public DNS alone) get the same row; `attachmentId` links the\n * attachment when one exists.\n */\nexport class Readiness extends Schema.Class<Readiness>(\"@domainkit/Storage/Readiness\")({\n domain: Schema.String,\n attachmentId: Schema.NullOr(Schema.String),\n ownerId: Schema.String,\n overall: Overall,\n requirements: Schema.Array(\n Schema.Struct({\n operationId: Schema.NullOr(Plan.OperationId),\n record: DnsRecord.Model,\n status: RequirementStatus,\n /** Encoded `Verify.Evidence` values. */\n evidence: Schema.Array(Schema.Unknown),\n }),\n ),\n /** Encoded `Verify.HostEvidence` values, keyed by `source` on merge. */\n host: Schema.Array(Schema.Unknown),\n /** When the current pending streak began; drives the backoff ladder. */\n pendingSince: Schema.NullOr(Schema.DateTimeUtcFromString),\n checkedAt: Schema.DateTimeUtcFromString,\n nextCheckAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n}) {}\n\n// ---------------------------------------------------------------------------------------------\n// Service\n// ---------------------------------------------------------------------------------------------\n\nexport interface Interface {\n readonly authorizations: {\n /**\n * Insert, or CAS-replace when `expectedId` is set: the row must exist under this owner with an\n * active revocation state, else `NotFound` / `Busy`.\n */\n readonly upsert: (input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n }) => Fx<Authorization>;\n readonly get: (id: string) => Fx<Authorization>;\n readonly credential: (id: string) => Fx<Credential>;\n readonly rotate: (id: string, credential: Credential) => Fx<void>;\n readonly promoteCapabilities: (id: string, capabilities: ReadonlyArray<Capability>) => Fx<void>;\n /**\n * Two-phase: mark `pending`, run `revoke` outside any transaction, then delete. A failed\n * `revoke` leaves the row pending; `recoverRevocations` finishes it later.\n */\n readonly revoke: <E, R>(\n id: string,\n revoke: Effect.Effect<void, E, R>,\n ) => Effect.Effect<void, Errors.DomainKitError | E, Principal.Service | R>;\n readonly recoverRevocations: <E, R>(\n revoke: (authorization: Authorization) => Effect.Effect<void, E, R>,\n ) => Effect.Effect<number, Errors.DomainKitError | E, Principal.Service | R>;\n };\n readonly connections: {\n readonly create: (authorizationId: string) => Fx<Connection>;\n readonly get: (id: string) => Fx<Connection>;\n readonly list: (filter?: { readonly provider?: string }) => Fx<ReadonlyArray<Connection>>;\n /** Fails `InvalidInput` while attachments still reference the connection. */\n readonly remove: (id: string) => Fx<void>;\n };\n readonly attachments: {\n /** One attachment per (owner, domain); a duplicate fails `InvalidInput`. */\n readonly create: (input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly target: unknown;\n }) => Fx<Attachment>;\n readonly get: (id: string) => Fx<Attachment>;\n readonly byDomain: (domain: string) => Fx<Option.Option<Attachment>>;\n readonly list: (connectionId: string) => Fx<ReadonlyArray<Attachment>>;\n readonly remove: (id: string) => Fx<void>;\n };\n readonly continuations: {\n readonly put: (continuation: Continuation) => Fx<void>;\n /** Read without spending; a late read fails `Expired`. */\n readonly get: (id: string) => Fx<Continuation>;\n /** Exactly-once: the second consume of the same id fails `NotFound`; a late one fails `Expired`. */\n readonly consume: (id: string) => Fx<Continuation>;\n };\n readonly attempts: {\n readonly create: (attempt: Attempt) => Fx<Attempt>;\n readonly get: (id: Plan.PlanId) => Fx<Attempt>;\n readonly byApproval: (id: Approval.ApprovalId) => Fx<Attempt>;\n readonly byReceipt: (id: Receipt.ReceiptId) => Fx<Attempt>;\n readonly latest: (attachmentId: string, kind: Plan.Kind) => Fx<Option.Option<Attempt>>;\n /** `planned` -> `approved`; approving again with the same approval id is a no-op, anything else fails `Stale`. */\n readonly approve: (id: Plan.PlanId, approval: Approval.Model) => Fx<Attempt>;\n /**\n * `planned` -> `rejected` (terminal). Rejecting again returns the row unchanged; any other\n * status fails `Stale`, `expired` fails `Expired`, and a digest mismatch fails `Stale`.\n */\n readonly reject: (\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Fx<Attempt>;\n /**\n * Atomic transition to `applying` with a lease from `approved`, `failed`, or an expired\n * `applying`; fails `Busy` while a lease is live and `Stale` from any other status.\n */\n readonly claim: (id: Plan.PlanId, lease: DateTime.Utc) => Fx<Attempt>;\n readonly complete: (id: Plan.PlanId, receipt: Receipt.Model) => Fx<Attempt>;\n readonly fail: (id: Plan.PlanId, message: string) => Fx<Attempt>;\n };\n readonly readiness: {\n /** One row per (owner, domain); `attachmentId`, when set, must exist for the owner. */\n readonly put: (readiness: Readiness) => Fx<void>;\n readonly get: (domain: string) => Fx<Option.Option<Readiness>>;\n };\n /** Single-flight guard keyed by string (credential refresh, apply). Fails `Busy` rather than waiting. */\n readonly withLock: <A, E, R>(\n key: string,\n effect: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | Errors.DomainKitError, R | Principal.Service>;\n}\n\nexport class Service extends Context.Service<Service, Interface>()(\"@domainkit/Storage\") {}\n\nexport interface MemoryOptions {\n /** Fault injection: runs before every mutation commits; failing here leaves state untouched. */\n readonly beforeCommit?: (operation: string) => Effect.Effect<void, Errors.DomainKitError>;\n}\n\n/** In-memory implementation for tests and local development. Not for production. */\nexport const layerMemory: Layer.Layer<Service> = Layer.sync(Service)(() => makeMemory());\n\n/** `layerMemory` with fault injection for storage-failure tests. */\nexport const layerMemoryWith = (options: MemoryOptions): Layer.Layer<Service> =>\n Layer.sync(Service)(() => makeMemory(options));\n\nexport { makeMemory };\n\n// ---------------------------------------------------------------------------------------------\n// Async adapter\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A Promise-shaped implementation for hosts that persist without Effect. Every method takes the\n * principal explicitly. Rejections become `StorageFailed`; reject with a `DomainKit.Error` to keep\n * a typed reason. Two-phase revocation and locking are split into plain steps so no callback has\n * to run an Effect.\n */\nexport interface AsyncInterface {\n readonly authorizations: {\n readonly upsert: (\n principal: Principal.Interface,\n input: {\n readonly authorization: Authorization;\n readonly credential: Credential;\n readonly expectedId?: string;\n },\n ) => Promise<Authorization>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Authorization>;\n readonly credential: (principal: Principal.Interface, id: string) => Promise<Credential>;\n readonly rotate: (\n principal: Principal.Interface,\n id: string,\n credential: Credential,\n ) => Promise<void>;\n readonly promoteCapabilities: (\n principal: Principal.Interface,\n id: string,\n capabilities: ReadonlyArray<Capability>,\n ) => Promise<void>;\n /** Mark `pending` durably; must be idempotent. */\n readonly prepareRevocation: (\n principal: Principal.Interface,\n id: string,\n ) => Promise<Authorization>;\n /** Delete the authorization after the provider confirmed revocation. */\n readonly completeRevocation: (principal: Principal.Interface, id: string) => Promise<void>;\n readonly pendingRevocations: (\n principal: Principal.Interface,\n ) => Promise<ReadonlyArray<Authorization>>;\n };\n readonly connections: {\n readonly create: (\n principal: Principal.Interface,\n authorizationId: string,\n ) => Promise<Connection>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Connection>;\n readonly list: (\n principal: Principal.Interface,\n filter?: { readonly provider?: string },\n ) => Promise<ReadonlyArray<Connection>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly attachments: {\n readonly create: (\n principal: Principal.Interface,\n input: {\n readonly connectionId: string;\n readonly domain: string;\n readonly zone: string;\n readonly target: unknown;\n },\n ) => Promise<Attachment>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Attachment>;\n readonly byDomain: (\n principal: Principal.Interface,\n domain: string,\n ) => Promise<Attachment | null>;\n readonly list: (\n principal: Principal.Interface,\n connectionId: string,\n ) => Promise<ReadonlyArray<Attachment>>;\n readonly remove: (principal: Principal.Interface, id: string) => Promise<void>;\n };\n readonly continuations: {\n readonly put: (principal: Principal.Interface, continuation: Continuation) => Promise<void>;\n readonly get: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n readonly consume: (principal: Principal.Interface, id: string) => Promise<Continuation>;\n };\n readonly attempts: {\n readonly create: (principal: Principal.Interface, attempt: Attempt) => Promise<Attempt>;\n readonly get: (principal: Principal.Interface, id: Plan.PlanId) => Promise<Attempt>;\n readonly byApproval: (\n principal: Principal.Interface,\n id: Approval.ApprovalId,\n ) => Promise<Attempt>;\n readonly byReceipt: (principal: Principal.Interface, id: Receipt.ReceiptId) => Promise<Attempt>;\n readonly latest: (\n principal: Principal.Interface,\n attachmentId: string,\n kind: Plan.Kind,\n ) => Promise<Attempt | null>;\n readonly approve: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n approval: Approval.Model,\n ) => Promise<Attempt>;\n readonly reject: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n input: {\n readonly digest: Plan.Digest;\n readonly actorId: string;\n readonly reason: string | null;\n },\n ) => Promise<Attempt>;\n readonly claim: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n lease: DateTime.Utc,\n ) => Promise<Attempt>;\n readonly complete: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n receipt: Receipt.Model,\n ) => Promise<Attempt>;\n readonly fail: (\n principal: Principal.Interface,\n id: Plan.PlanId,\n message: string,\n ) => Promise<Attempt>;\n };\n readonly readiness: {\n readonly put: (principal: Principal.Interface, readiness: Readiness) => Promise<void>;\n readonly get: (principal: Principal.Interface, domain: string) => Promise<Readiness | null>;\n };\n /** Return `false` when another holder has the key. */\n readonly acquireLock: (principal: Principal.Interface, key: string) => Promise<boolean>;\n readonly releaseLock: (principal: Principal.Interface, key: string) => Promise<void>;\n}\n\nconst storageFailed = (operation: string) => (cause: unknown) =>\n Errors.isDomainKitError(cause)\n ? cause\n : new Errors.DomainKitError({\n reason: new Reason.StorageFailed({\n operation,\n message: cause instanceof Error ? cause.message : String(cause),\n }),\n });\n\n/** Wraps a Promise-shaped implementation. Rejections become `StorageFailed`. */\nexport const fromAsync = (service: AsyncInterface): Interface => {\n const call = <A>(operation: string, run: (principal: Principal.Interface) => Promise<A>): Fx<A> =>\n Effect.flatMap(Principal.Service, (principal) =>\n Effect.tryPromise({ try: () => run(principal), catch: storageFailed(operation) }),\n );\n const option = <A>(\n operation: string,\n run: (principal: Principal.Interface) => Promise<A | null>,\n ) => call(operation, run).pipe(Effect.map(Option.fromNullishOr));\n return {\n authorizations: {\n upsert: (input) =>\n call(\"authorizations.upsert\", (p) => service.authorizations.upsert(p, input)),\n get: (id) => call(\"authorizations.get\", (p) => service.authorizations.get(p, id)),\n credential: (id) =>\n call(\"authorizations.credential\", (p) => service.authorizations.credential(p, id)),\n rotate: (id, credential) =>\n call(\"authorizations.rotate\", (p) => service.authorizations.rotate(p, id, credential)),\n promoteCapabilities: (id, capabilities) =>\n call(\"authorizations.promoteCapabilities\", (p) =>\n service.authorizations.promoteCapabilities(p, id, capabilities),\n ),\n revoke: (id, revoke) =>\n call(\"authorizations.prepareRevocation\", (p) =>\n service.authorizations.prepareRevocation(p, id),\n ).pipe(\n Effect.flatMap(() => revoke),\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, id),\n ),\n ),\n ),\n recoverRevocations: (revoke) =>\n call(\"authorizations.pendingRevocations\", (p) =>\n service.authorizations.pendingRevocations(p),\n ).pipe(\n Effect.flatMap((pending) =>\n Effect.forEach(pending, (authorization) =>\n revoke(authorization).pipe(\n Effect.flatMap(() =>\n call(\"authorizations.completeRevocation\", (p) =>\n service.authorizations.completeRevocation(p, authorization.id),\n ),\n ),\n ),\n ),\n ),\n Effect.map((completed) => completed.length),\n ),\n },\n connections: {\n create: (authorizationId) =>\n call(\"connections.create\", (p) => service.connections.create(p, authorizationId)),\n get: (id) => call(\"connections.get\", (p) => service.connections.get(p, id)),\n list: (filter) => call(\"connections.list\", (p) => service.connections.list(p, filter)),\n remove: (id) => call(\"connections.remove\", (p) => service.connections.remove(p, id)),\n },\n attachments: {\n create: (input) => call(\"attachments.create\", (p) => service.attachments.create(p, input)),\n get: (id) => call(\"attachments.get\", (p) => service.attachments.get(p, id)),\n byDomain: (domain) =>\n option(\"attachments.byDomain\", (p) => service.attachments.byDomain(p, domain)),\n list: (connectionId) =>\n call(\"attachments.list\", (p) => service.attachments.list(p, connectionId)),\n remove: (id) => call(\"attachments.remove\", (p) => service.attachments.remove(p, id)),\n },\n continuations: {\n put: (continuation) =>\n call(\"continuations.put\", (p) => service.continuations.put(p, continuation)),\n get: (id) => call(\"continuations.get\", (p) => service.continuations.get(p, id)),\n consume: (id) => call(\"continuations.consume\", (p) => service.continuations.consume(p, id)),\n },\n attempts: {\n create: (attempt) => call(\"attempts.create\", (p) => service.attempts.create(p, attempt)),\n get: (id) => call(\"attempts.get\", (p) => service.attempts.get(p, id)),\n byApproval: (id) => call(\"attempts.byApproval\", (p) => service.attempts.byApproval(p, id)),\n byReceipt: (id) => call(\"attempts.byReceipt\", (p) => service.attempts.byReceipt(p, id)),\n latest: (attachmentId, kind) =>\n option(\"attempts.latest\", (p) => service.attempts.latest(p, attachmentId, kind)),\n approve: (id, approval) =>\n call(\"attempts.approve\", (p) => service.attempts.approve(p, id, approval)),\n reject: (id, input) => call(\"attempts.reject\", (p) => service.attempts.reject(p, id, input)),\n claim: (id, lease) => call(\"attempts.claim\", (p) => service.attempts.claim(p, id, lease)),\n complete: (id, receipt) =>\n call(\"attempts.complete\", (p) => service.attempts.complete(p, id, receipt)),\n fail: (id, message) => call(\"attempts.fail\", (p) => service.attempts.fail(p, id, message)),\n },\n readiness: {\n put: (readiness) => call(\"readiness.put\", (p) => service.readiness.put(p, readiness)),\n get: (domain) => option(\"readiness.get\", (p) => service.readiness.get(p, domain)),\n },\n withLock: (key, effect) =>\n Effect.acquireRelease(\n call(\"acquireLock\", (p) => service.acquireLock(p, key)).pipe(\n Effect.flatMap((acquired) =>\n acquired ? Effect.void : Errors.fail(new Reason.Busy({ key })),\n ),\n ),\n () => call(\"releaseLock\", (p) => service.releaseLock(p, key)).pipe(Effect.ignore),\n ).pipe(\n Effect.flatMap(() => effect),\n Effect.scoped,\n ),\n };\n};\n\nexport const layerFromAsync = (service: AsyncInterface): Layer.Layer<Service> =>\n Layer.succeed(Service)(fromAsync(service));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,aAAa,OAAO,SAAS,CAAC,YAAY,WAAW,CAAC;AAGnE,MAAa,aAAa,OAAO,SAAS;CAAC;CAAS;CAAS;AAAa,CAAC;;AAI3E,IAAa,aAAb,cAAgC,OAAO,MAAkB,+BAA+B,CAAC,CAAC;CACxF,YAAY,OAAO;CACnB,WAAW,OAAO,OAAO,OAAO,qBAAqB;CACrD,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,gBAAb,cAAmC,OAAO,MAAqB,kCAAkC,CAAC,CAAC;CACjG,IAAI,OAAO;CACX,SAAS,OAAO;CAChB,UAAU,OAAO;CACjB,QAAQ;CACR,cAAc,OAAO,MAA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c,IAAI,CAAC;GACjF,UAAU,IAAI,aACZ,KAAK,qBAAqB,MAAM,QAAQ,SAAS,QAAQ,GAAG,IAAI,QAAQ,CAAC;GAC3E,SAAS,IAAI,UAAU,KAAK,oBAAoB,MAAM,QAAQ,SAAS,OAAO,GAAG,IAAI,KAAK,CAAC;GAC3F,QAAQ,IAAI,UAAU,KAAK,mBAAmB,MAAM,QAAQ,SAAS,MAAM,GAAG,IAAI,KAAK,CAAC;GACxF,WAAW,IAAI,YACb,KAAK,sBAAsB,MAAM,QAAQ,SAAS,SAAS,GAAG,IAAI,OAAO,CAAC;GAC5E,OAAO,IAAI,YAAY,KAAK,kBAAkB,MAAM,QAAQ,SAAS,KAAK,GAAG,IAAI,OAAO,CAAC;EAC3F;EACA,WAAW;GACT,MAAM,cAAc,KAAK,kBAAkB,MAAM,QAAQ,UAAU,IAAI,GAAG,SAAS,CAAC;GACpF,MAAM,WAAW,OAAO,kBAAkB,MAAM,QAAQ,UAAU,IAAI,GAAG,MAAM,CAAC;EAClF;EACA,WAAW,KAAK,WACd,OAAO,eACL,KAAK,gBAAgB,MAAM,QAAQ,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,KACtD,OAAO,SAAS,aACd,WAAW,OAAO,OAAOC,KAAY,IAAIC,KAAY,EAAE,IAAI,CAAC,CAAC,CAC/D,CACF,SACM,KAAK,gBAAgB,MAAM,QAAQ,YAAY,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO,MAAM,CAClF,CAAC,CAAC,KACA,OAAO,cAAc,MAAM,GAC3B,OAAO,MACT;CACJ;AACF;AAEA,MAAa,kBAAkB,YAC7B,MAAM,QAAQ,OAAO,CAAC,CAAC,UAAU,OAAO,CAAC"}
|
package/dist/Testing.mjs
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { __exportAll } from "./_virtual/_rolldown/runtime.mjs";
|
|
2
|
+
import { decode, fromString, fromStringUnsafe, isWithin } from "./DomainName.mjs";
|
|
3
|
+
import { ns } from "./DnsRecord.mjs";
|
|
4
|
+
import { NotFound, ProviderRejected, ProviderUnavailable, Unauthenticated } from "./Reason.mjs";
|
|
5
|
+
import { fail } from "./internal/error.mjs";
|
|
6
|
+
import { make } from "./Principal.mjs";
|
|
7
|
+
import { make as make$1, resolveAmong, tokenAuth } from "./Provider.mjs";
|
|
8
|
+
import { Outcome, Service } from "./Resolver.mjs";
|
|
9
|
+
import { layerMemory } from "./Storage.mjs";
|
|
10
|
+
import { layerMemory as layerMemory$1 } from "./DomainKit.mjs";
|
|
11
|
+
import { Identity, toWebHandler } from "./Server.mjs";
|
|
12
|
+
import { capabilities, fromFetch } from "./Transport.mjs";
|
|
13
|
+
import { provider as provider$1 } from "./internal/conformance/provider.mjs";
|
|
14
|
+
import { storage as storage$1 } from "./internal/conformance/storage.mjs";
|
|
15
|
+
import { DateTime, Effect, Layer, Redacted, Schema } from "effect";
|
|
16
|
+
//#region src/Testing.ts
|
|
17
|
+
/**
|
|
18
|
+
* domainkit/testing — fakes and conformance runners so hosts test against the seam instead of
|
|
19
|
+
* stubbing global fetch.
|
|
20
|
+
*/
|
|
21
|
+
var Testing_exports = /* @__PURE__ */ __exportAll({
|
|
22
|
+
conformance: () => conformance,
|
|
23
|
+
fakeRecords: () => fakeRecords,
|
|
24
|
+
principal: () => principal,
|
|
25
|
+
provider: () => provider,
|
|
26
|
+
resolver: () => resolver,
|
|
27
|
+
storage: () => storage,
|
|
28
|
+
transport: () => transport
|
|
29
|
+
});
|
|
30
|
+
/** In-memory Storage. Same as `Storage.layerMemory`; re-exported for discoverability. */
|
|
31
|
+
const storage = layerMemory;
|
|
32
|
+
const principal = make({
|
|
33
|
+
ownerId: "org_test",
|
|
34
|
+
actorId: "user_test"
|
|
35
|
+
});
|
|
36
|
+
/** Every fake zone created in this process, so `resolver()` can answer from them. */
|
|
37
|
+
const registry = /* @__PURE__ */ new Set();
|
|
38
|
+
/** Account context carries `account`; target context carries `zone`. One schema covers both. */
|
|
39
|
+
const Context$1 = Schema.Struct({
|
|
40
|
+
account: Schema.optionalKey(Schema.String),
|
|
41
|
+
zone: Schema.optionalKey(Schema.String)
|
|
42
|
+
});
|
|
43
|
+
const TargetContext = Schema.Struct({ zone: Schema.String });
|
|
44
|
+
/** A provider definition with a token method (and optional OAuth) over in-memory zones. */
|
|
45
|
+
const provider = (options = {}) => {
|
|
46
|
+
const id = options.id ?? "fake";
|
|
47
|
+
const zones = /* @__PURE__ */ new Map();
|
|
48
|
+
let nextId = 1;
|
|
49
|
+
let writes = 0;
|
|
50
|
+
let revokedCount = 0;
|
|
51
|
+
const issued = [];
|
|
52
|
+
for (const name of options.zones ?? ["example.com"]) {
|
|
53
|
+
const normalized = fromStringUnsafe(name);
|
|
54
|
+
const zone = {
|
|
55
|
+
name: normalized,
|
|
56
|
+
nameservers: options.nameservers?.[name] ?? options.nameservers?.[normalized] ?? [`ns1.${normalized}`, `ns2.${normalized}`],
|
|
57
|
+
rows: []
|
|
58
|
+
};
|
|
59
|
+
zones.set(zone.name, zone);
|
|
60
|
+
registry.add(zone);
|
|
61
|
+
}
|
|
62
|
+
for (const { zone: name, record } of options.records ?? []) {
|
|
63
|
+
const zone = zones.get(fromStringUnsafe(name));
|
|
64
|
+
if (zone === void 0) throw new Error(`Fake provider ${id} has no zone ${name}`);
|
|
65
|
+
zone.rows.push({
|
|
66
|
+
id: `${id}-${nextId++}`,
|
|
67
|
+
record
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const issue = (prefix) => {
|
|
71
|
+
const secret = `${prefix}-${issued.length + 1}`;
|
|
72
|
+
issued.push(secret);
|
|
73
|
+
return {
|
|
74
|
+
secret: Redacted.make(secret),
|
|
75
|
+
context: { account: id },
|
|
76
|
+
expiresAt: null
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
const zoneOf = (target) => Effect.suspend(() => {
|
|
80
|
+
const decoded = Schema.decodeUnknownOption(TargetContext)(target.context);
|
|
81
|
+
const zone = decoded._tag === "Some" ? zones.get(decoded.value.zone) : void 0;
|
|
82
|
+
return zone === void 0 ? fail(new NotFound({
|
|
83
|
+
entity: "zone",
|
|
84
|
+
id: target.zone
|
|
85
|
+
})) : Effect.succeed(zone);
|
|
86
|
+
});
|
|
87
|
+
const targets = () => [...zones.values()].map((zone) => ({
|
|
88
|
+
zone: zone.name,
|
|
89
|
+
context: { zone: zone.name },
|
|
90
|
+
label: zone.name,
|
|
91
|
+
nameservers: zone.nameservers
|
|
92
|
+
}));
|
|
93
|
+
return {
|
|
94
|
+
...make$1({
|
|
95
|
+
id,
|
|
96
|
+
name: `Fake ${id}`,
|
|
97
|
+
context: Context$1,
|
|
98
|
+
contextVersion: "fake.v1",
|
|
99
|
+
auth: {
|
|
100
|
+
token: tokenAuth({
|
|
101
|
+
label: "Token (fake)",
|
|
102
|
+
requiredCapabilities: ["dns:read", "dns:write"],
|
|
103
|
+
fields: Schema.Struct({ token: Schema.RedactedFromValue(Schema.String) }),
|
|
104
|
+
authenticate: ({ token }) => Redacted.value(token).length === 0 ? fail(new Unauthenticated({ message: "fake provider rejected an empty token" })) : Effect.succeed({
|
|
105
|
+
secret: token,
|
|
106
|
+
context: { account: id },
|
|
107
|
+
expiresAt: null
|
|
108
|
+
})
|
|
109
|
+
}),
|
|
110
|
+
...options.oauth === true ? { oauth: {
|
|
111
|
+
label: "Sign in (fake)",
|
|
112
|
+
scopes: ["dns"],
|
|
113
|
+
start: (input) => Effect.succeed({ authorizationUrl: `${input.callbackUrl}?${new URLSearchParams({
|
|
114
|
+
state: input.state,
|
|
115
|
+
code: "fake-code"
|
|
116
|
+
})}` }),
|
|
117
|
+
complete: (input) => input.code === "fake-code" ? Effect.map(DateTime.now, (now) => ({
|
|
118
|
+
...issue("oauth"),
|
|
119
|
+
expiresAt: DateTime.add(now, { hours: 1 })
|
|
120
|
+
})) : fail(new Unauthenticated({ message: "fake provider rejected the code" })),
|
|
121
|
+
refresh: (credential) => Redacted.value(credential.secret).startsWith("revoked") ? fail(new Unauthenticated({ message: "fake refresh token was revoked" })) : Effect.map(DateTime.now, (now) => ({
|
|
122
|
+
...issue("oauth"),
|
|
123
|
+
expiresAt: DateTime.add(now, { hours: 1 })
|
|
124
|
+
})),
|
|
125
|
+
revoke: () => Effect.sync(() => void (revokedCount += 1))
|
|
126
|
+
} } : {}
|
|
127
|
+
},
|
|
128
|
+
session: () => ({
|
|
129
|
+
capabilities: () => Effect.succeed(["dns:read", "dns:write"]),
|
|
130
|
+
listTargets: () => Effect.succeed(targets()),
|
|
131
|
+
resolveTarget: (domain) => Effect.map(decode(domain), (name) => resolveAmong(name, targets())),
|
|
132
|
+
dns: (target) => ({
|
|
133
|
+
list: () => Effect.map(zoneOf(target), (zone) => zone.rows.map(({ id: providerRecordId, record }) => ({
|
|
134
|
+
record,
|
|
135
|
+
providerRecordId
|
|
136
|
+
}))),
|
|
137
|
+
create: (_zone, record) => Effect.gen(function* () {
|
|
138
|
+
const zone = yield* zoneOf(target);
|
|
139
|
+
const index = writes;
|
|
140
|
+
writes += 1;
|
|
141
|
+
if (options.failWrite?.(index) === true) return yield* fail(new ProviderUnavailable({
|
|
142
|
+
provider: id,
|
|
143
|
+
message: `fake provider failed write ${index}`
|
|
144
|
+
}));
|
|
145
|
+
if (!isWithin(record.name, zone.name)) return yield* fail(new ProviderRejected({
|
|
146
|
+
provider: id,
|
|
147
|
+
message: `${record.name} is outside ${zone.name}`
|
|
148
|
+
}));
|
|
149
|
+
const providerRecordId = `${id}-${nextId++}`;
|
|
150
|
+
zone.rows.push({
|
|
151
|
+
id: providerRecordId,
|
|
152
|
+
record
|
|
153
|
+
});
|
|
154
|
+
return { providerRecordId };
|
|
155
|
+
}),
|
|
156
|
+
get: (_zone, providerRecordId) => Effect.map(zoneOf(target), (zone) => zone.rows.find((row) => row.id === providerRecordId)?.record ?? null),
|
|
157
|
+
delete: (_zone, providerRecordId) => Effect.map(zoneOf(target), (zone) => {
|
|
158
|
+
const index = zone.rows.findIndex((row) => row.id === providerRecordId);
|
|
159
|
+
if (index >= 0) zone.rows.splice(index, 1);
|
|
160
|
+
})
|
|
161
|
+
})
|
|
162
|
+
})
|
|
163
|
+
}),
|
|
164
|
+
records: (zone) => zones.get(fromStringUnsafe(zone))?.rows.map(({ record }) => record) ?? [],
|
|
165
|
+
issued: () => issued,
|
|
166
|
+
revoked: () => revokedCount
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
/** NS records for every fake zone named `name`, so `resolver()` can answer authority queries. */
|
|
170
|
+
const fakeNameservers = (name) => [...registry].filter((zone) => zone.name === name).flatMap((zone) => zone.nameservers.map((nameserver) => ns({
|
|
171
|
+
name: zone.name,
|
|
172
|
+
nameserver
|
|
173
|
+
})));
|
|
174
|
+
/** Records every fake provider currently holds for `name`, across all fake zones. */
|
|
175
|
+
const fakeRecords = (name) => [...registry].flatMap((zone) => zone.rows.map(({ record }) => record)).filter((record) => record.name === name);
|
|
176
|
+
/**
|
|
177
|
+
* A resolver answering from the fake providers' zones, or from an explicit table. Every answer
|
|
178
|
+
* is attributed to the resolver named `fake`.
|
|
179
|
+
*/
|
|
180
|
+
const resolver = (answers) => Layer.succeed(Service)({ resolve: (name, type) => Effect.sync(() => {
|
|
181
|
+
const normalized = fromString(name);
|
|
182
|
+
const lookup = normalized._tag === "Some" ? normalized.value : name;
|
|
183
|
+
const records = (answers === void 0 ? [...fakeRecords(lookup), ...fakeNameservers(lookup)] : answers.filter((entry) => entry.name === lookup).flatMap((entry) => entry.records)).filter((record) => (record._tag === "Opaque" ? record.type : record._tag) === type);
|
|
184
|
+
return [Outcome.Answered({ answer: {
|
|
185
|
+
resolver: "fake",
|
|
186
|
+
records,
|
|
187
|
+
negative: records.length === 0,
|
|
188
|
+
ttl: 60
|
|
189
|
+
} })];
|
|
190
|
+
}) });
|
|
191
|
+
/**
|
|
192
|
+
* A transport over an in-memory `domainkit/server` and memory Storage, recording every call. What
|
|
193
|
+
* `@domainkit/react` tests render against, instead of stubbing global `fetch`.
|
|
194
|
+
*/
|
|
195
|
+
const transport = (options = {}) => {
|
|
196
|
+
const fake = provider(options.provider);
|
|
197
|
+
const { handler } = toWebHandler(layerMemory$1({
|
|
198
|
+
providers: [fake],
|
|
199
|
+
resolver: resolver()
|
|
200
|
+
}).pipe(Layer.merge(Layer.succeed(Identity)({ principal: () => Effect.succeed(principal) }))));
|
|
201
|
+
const live = fromFetch("http://domainkit.test", {
|
|
202
|
+
fetch: (input, init) => handler(new Request(input, init)),
|
|
203
|
+
...options.capabilities === void 0 ? {} : { capabilities: options.capabilities }
|
|
204
|
+
});
|
|
205
|
+
const calls = [];
|
|
206
|
+
return {
|
|
207
|
+
...Object.fromEntries(capabilities(live).map((capability) => [capability, Object.fromEntries(Object.entries(live[capability]).map(([name, method]) => [name, (...args) => Effect.suspend(() => {
|
|
208
|
+
calls.push({
|
|
209
|
+
method: `${capability}.${name}`,
|
|
210
|
+
input: args.length > 1 ? args : args[0]
|
|
211
|
+
});
|
|
212
|
+
return method(...args);
|
|
213
|
+
})]))])),
|
|
214
|
+
calls
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
const conformance = {
|
|
218
|
+
/** Runs every Storage invariant (tenant isolation, leases, exactly-once continuations, revocation recovery). */
|
|
219
|
+
storage: storage$1,
|
|
220
|
+
/** Runs create/readback/cleanup, exact-noop, conflict, stale-plan, partial-apply against a real provider definition. */
|
|
221
|
+
provider: provider$1
|
|
222
|
+
};
|
|
223
|
+
//#endregion
|
|
224
|
+
export { Testing_exports, conformance, fakeRecords, principal, provider, resolver, storage, transport };
|
|
225
|
+
|
|
226
|
+
//# sourceMappingURL=Testing.mjs.map
|