@party-stack/ontology-backend 0.0.0-stage → 0.2.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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +148 -2
  3. package/lib/actions.d.ts +47 -0
  4. package/lib/actions.d.ts.map +1 -0
  5. package/lib/actions.js +306 -0
  6. package/lib/actions.js.map +1 -0
  7. package/lib/clients.d.ts +236 -0
  8. package/lib/clients.d.ts.map +1 -0
  9. package/lib/clients.js +211 -0
  10. package/lib/clients.js.map +1 -0
  11. package/lib/delivery.d.ts +746 -0
  12. package/lib/delivery.d.ts.map +1 -0
  13. package/lib/delivery.js +863 -0
  14. package/lib/delivery.js.map +1 -0
  15. package/lib/description.d.ts +29 -0
  16. package/lib/description.d.ts.map +1 -0
  17. package/lib/description.js +28 -0
  18. package/lib/description.js.map +1 -0
  19. package/lib/encrypted.d.ts +41 -0
  20. package/lib/encrypted.d.ts.map +1 -0
  21. package/lib/encrypted.js +111 -0
  22. package/lib/encrypted.js.map +1 -0
  23. package/lib/errors.d.ts +106 -0
  24. package/lib/errors.d.ts.map +1 -0
  25. package/lib/errors.js +275 -0
  26. package/lib/errors.js.map +1 -0
  27. package/lib/fulfillment.d.ts +25 -0
  28. package/lib/fulfillment.d.ts.map +1 -0
  29. package/lib/fulfillment.js +99 -0
  30. package/lib/fulfillment.js.map +1 -0
  31. package/lib/index.d.ts +297 -0
  32. package/lib/index.d.ts.map +1 -0
  33. package/lib/index.js +91 -0
  34. package/lib/index.js.map +1 -0
  35. package/lib/maintenance.d.ts +11 -0
  36. package/lib/maintenance.d.ts.map +1 -0
  37. package/lib/maintenance.js +24 -0
  38. package/lib/maintenance.js.map +1 -0
  39. package/lib/meta.d.ts +26 -0
  40. package/lib/meta.d.ts.map +1 -0
  41. package/lib/meta.js +213 -0
  42. package/lib/meta.js.map +1 -0
  43. package/lib/owned.d.ts +74 -0
  44. package/lib/owned.d.ts.map +1 -0
  45. package/lib/owned.js +593 -0
  46. package/lib/owned.js.map +1 -0
  47. package/lib/policy/indexes.d.ts +12 -0
  48. package/lib/policy/indexes.d.ts.map +1 -0
  49. package/lib/policy/indexes.js +113 -0
  50. package/lib/policy/indexes.js.map +1 -0
  51. package/lib/policy/planner.d.ts +10 -0
  52. package/lib/policy/planner.d.ts.map +1 -0
  53. package/lib/policy/planner.js +118 -0
  54. package/lib/policy/planner.js.map +1 -0
  55. package/lib/policy/view.d.ts +31 -0
  56. package/lib/policy/view.d.ts.map +1 -0
  57. package/lib/policy/view.js +173 -0
  58. package/lib/policy/view.js.map +1 -0
  59. package/lib/policy.d.ts +47 -0
  60. package/lib/policy.d.ts.map +1 -0
  61. package/lib/policy.js +100 -0
  62. package/lib/policy.js.map +1 -0
  63. package/lib/protocol.d.ts +570 -0
  64. package/lib/protocol.d.ts.map +1 -0
  65. package/lib/protocol.js +144 -0
  66. package/lib/protocol.js.map +1 -0
  67. package/lib/query.d.ts +33 -0
  68. package/lib/query.d.ts.map +1 -0
  69. package/lib/query.js +51 -0
  70. package/lib/query.js.map +1 -0
  71. package/lib/references.d.ts +8 -0
  72. package/lib/references.d.ts.map +1 -0
  73. package/lib/references.js +41 -0
  74. package/lib/references.js.map +1 -0
  75. package/lib/storage.d.ts +55 -0
  76. package/lib/storage.d.ts.map +1 -0
  77. package/lib/storage.js +168 -0
  78. package/lib/storage.js.map +1 -0
  79. package/lib/subset.d.ts +19 -0
  80. package/lib/subset.d.ts.map +1 -0
  81. package/lib/subset.js +150 -0
  82. package/lib/subset.js.map +1 -0
  83. package/lib/subsetSchema.d.ts +10 -0
  84. package/lib/subsetSchema.d.ts.map +1 -0
  85. package/lib/subsetSchema.js +20 -0
  86. package/lib/subsetSchema.js.map +1 -0
  87. package/package.json +72 -3
package/lib/errors.js ADDED
@@ -0,0 +1,275 @@
1
+ import { OntologyStorageError } from "@party-stack/ontology-storage";
2
+ import { Predicate, Redacted, Schema, SchemaIssue } from "effect";
3
+ import { BlobStorageError } from "@party-stack/ontology-storage/blobs";
4
+ import { HttpClientError } from "effect/http";
5
+ import { RpcClientError } from "effect/rpc";
6
+ //#region src/errors.ts
7
+ const ValidationIssueSchema = Schema.Struct({
8
+ message: Schema.String,
9
+ path: Schema.optional(Schema.Array(Schema.Union([Schema.String, Schema.Number]))),
10
+ code: Schema.optional(Schema.String),
11
+ category: Schema.optional(Schema.Literals([
12
+ "input",
13
+ "reference",
14
+ "custom"
15
+ ])),
16
+ source: Schema.optional(Schema.Literals([
17
+ "parameter",
18
+ "submission",
19
+ "user-facing"
20
+ ])),
21
+ messageSource: Schema.optional(Schema.Literals(["standard", "configured"]))
22
+ });
23
+ const ValidationReportSchema = Schema.Union([Schema.Struct({ certain: Schema.Literal(false) }), Schema.Struct({
24
+ certain: Schema.Literal(true),
25
+ value: Schema.Union([Schema.Struct({
26
+ kind: Schema.Literal("ok"),
27
+ value: Schema.Void
28
+ }), Schema.Struct({
29
+ kind: Schema.Literal("err"),
30
+ value: Schema.Array(ValidationIssueSchema)
31
+ })])
32
+ })]);
33
+ const BackendErrorKindSchema = Schema.Literals([
34
+ "Unauthenticated",
35
+ "Forbidden",
36
+ "NotFound",
37
+ "ValidationFailed",
38
+ "InvalidRequest",
39
+ "InvalidResponse",
40
+ "InvalidConfiguration",
41
+ "Conflict",
42
+ "NotImplemented",
43
+ "RateLimited",
44
+ "Unavailable",
45
+ "Internal",
46
+ "HistoryExpired",
47
+ "SessionExpired",
48
+ "SessionReplaced",
49
+ "ViewReplaced",
50
+ "ResultExpired",
51
+ "SourceMismatch",
52
+ "SchemaMismatch"
53
+ ]);
54
+ const Fields = {
55
+ operation: Schema.String,
56
+ kind: BackendErrorKindSchema,
57
+ message: Schema.String,
58
+ retryable: Schema.Boolean,
59
+ actionOutcome: Schema.optional(Schema.Literals(["not-committed", "unknown"])),
60
+ retryAfterMs: Schema.optional(Schema.Finite),
61
+ issues: Schema.optional(Schema.Array(ValidationIssueSchema)),
62
+ cause: Schema.optional(Schema.Defect())
63
+ };
64
+ /** Shared wire schema; hooks narrow the kind without duplicating error classes. */
65
+ var BackendError = class extends Schema.TaggedError()("BackendError", Fields) {
66
+ constructor(properties) {
67
+ super(properties);
68
+ }
69
+ };
70
+ /** HTTP bindings share these statuses; RPC still carries the typed error schema. */
71
+ const backendErrorStatus = (error) => ({
72
+ Unauthenticated: 401,
73
+ Forbidden: 403,
74
+ NotFound: 404,
75
+ ValidationFailed: 422,
76
+ InvalidRequest: 400,
77
+ InvalidResponse: 502,
78
+ InvalidConfiguration: 500,
79
+ Conflict: 409,
80
+ NotImplemented: 501,
81
+ RateLimited: 429,
82
+ Unavailable: 503,
83
+ Internal: 500,
84
+ HistoryExpired: 409,
85
+ SessionExpired: 409,
86
+ SessionReplaced: 409,
87
+ ViewReplaced: 409,
88
+ ResultExpired: 409,
89
+ SourceMismatch: 409,
90
+ SchemaMismatch: 409
91
+ })[error.kind];
92
+ const unauthenticated = (message = "Authentication is required.", options) => new BackendError({
93
+ operation: "authentication",
94
+ kind: "Unauthenticated",
95
+ message,
96
+ retryable: false,
97
+ actionOutcome: "not-committed",
98
+ cause: options?.cause
99
+ });
100
+ const isUnauthenticatedError = (error) => error instanceof BackendError && error.kind === "Unauthenticated";
101
+ /** Unknown outcomes apply to dispatch/execution failures, never ordinary rejections. */
102
+ const isUnknownActionOutcome = (error) => error.actionOutcome === "unknown" || error.actionOutcome === void 0 && (error.kind === "Unavailable" || error.kind === "Internal" || error.kind === "InvalidResponse");
103
+ const ProviderFailure = Schema.Struct({
104
+ reason: Schema.optional(Schema.Unknown),
105
+ cause: Schema.optional(Schema.Unknown),
106
+ response: Schema.optional(Schema.Struct({
107
+ status: Schema.Number,
108
+ headers: Schema.optional(Schema.Record(Schema.String, Schema.String))
109
+ })),
110
+ retryAfterMs: Schema.optional(Schema.Finite),
111
+ status: Schema.optional(Schema.Number),
112
+ statusCode: Schema.optional(Schema.Number),
113
+ errorCode: Schema.optional(Schema.String),
114
+ errorName: Schema.optional(Schema.String),
115
+ code: Schema.optional(Schema.String),
116
+ parameters: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
117
+ });
118
+ /** Normalize SDK failures. No provider message/body is made public by this classifier. */
119
+ function classifyBackendFailure(operation, cause) {
120
+ if (cause instanceof BackendError) return cause;
121
+ if (cause instanceof RpcClientError.RpcClientError && cause.reason._tag === "RpcClientDefect" && (cause.reason.message === "HTTP response ended before RPC request completed" || cause.reason.message === "Received empty HTTP response from RPC server")) return new BackendError({
122
+ operation,
123
+ kind: "Unavailable",
124
+ message: "The RPC connection was interrupted.",
125
+ retryable: true,
126
+ actionOutcome: "unknown",
127
+ cause: Redacted.make(cause)
128
+ });
129
+ if (cause instanceof RpcClientError.RpcClientError && cause.reason._tag === "RpcClientDefect" || cause instanceof HttpClientError.HttpClientError && cause.reason._tag === "DecodeError") return new BackendError({
130
+ operation,
131
+ kind: "InvalidResponse",
132
+ message: "The source returned an invalid response.",
133
+ retryable: false,
134
+ actionOutcome: "unknown",
135
+ cause: Redacted.make(cause)
136
+ });
137
+ if (cause instanceof HttpClientError.HttpClientError && (cause.reason._tag === "EncodeError" || cause.reason._tag === "InvalidUrlError")) return new BackendError({
138
+ operation,
139
+ kind: cause.reason._tag === "EncodeError" ? "InvalidRequest" : "InvalidConfiguration",
140
+ message: "The request could not be constructed.",
141
+ retryable: false,
142
+ actionOutcome: "not-committed",
143
+ cause: Redacted.make(cause)
144
+ });
145
+ const blob = cause instanceof BlobStorageError ? cause : cause instanceof OntologyStorageError && cause.reason._tag === "BlobStorageError" ? cause.reason : void 0;
146
+ if (blob) return new BackendError({
147
+ operation,
148
+ kind: blob.kind === "NotFound" ? "NotFound" : blob.kind === "InvalidValue" ? "InvalidRequest" : blob.kind === "Busy" || blob.kind === "Conflict" ? "Conflict" : "Unavailable",
149
+ message: blob.kind === "NotFound" ? "Attachment is unavailable." : blob.kind === "Busy" ? "Attachment upload is still in progress." : blob.kind === "Conflict" ? "Attachment state conflicts with this operation." : blob.kind === "InvalidValue" ? "Invalid attachment value." : "Attachment storage is unavailable.",
150
+ retryable: blob.kind === "Busy" || blob.kind === "Bytes",
151
+ cause: Redacted.make(cause)
152
+ });
153
+ if (cause instanceof OntologyStorageError) {
154
+ const reason = cause.reason;
155
+ const kind = reason._tag === "QueryError" ? "InvalidRequest" : reason._tag === "ConfigurationError" || reason._tag === "IndexError" ? "InvalidConfiguration" : reason._tag === "DefinitionMismatch" || reason._tag === "SchemaMismatch" ? "SchemaMismatch" : reason._tag === "UniqueConstraint" ? "Conflict" : reason._tag === "StorageError" || reason._tag === "TransactionError" && reason.kind === "Backend" ? "Unavailable" : "Internal";
156
+ return new BackendError({
157
+ operation,
158
+ kind,
159
+ message: kind === "InvalidRequest" ? "Invalid storage query." : kind === "SchemaMismatch" ? "Storage schema changed; migrate or reset explicitly." : "Storage operation failed.",
160
+ retryable: cause.isRetryable,
161
+ cause: Redacted.make(cause)
162
+ });
163
+ }
164
+ let candidate = cause;
165
+ let value;
166
+ for (let depth = 0; depth < 5; depth++) {
167
+ if (candidate instanceof BackendError) return candidate;
168
+ const decoded = Schema.decodeUnknownOption(ProviderFailure)(candidate);
169
+ if (decoded._tag === "None") break;
170
+ value = decoded.value;
171
+ if (value.cause instanceof BackendError) return value.cause;
172
+ if (value.status !== void 0 || value.statusCode !== void 0 || value.errorCode !== void 0 || value.code !== void 0 || value.errorName !== void 0 || value.response) break;
173
+ candidate = value.reason ?? value.cause;
174
+ }
175
+ const status = value?.status ?? value?.statusCode ?? value?.response?.status;
176
+ const code = value?.errorCode ?? value?.code;
177
+ const name = value?.errorName?.split(":").at(-1);
178
+ const kind = status === 501 ? "NotImplemented" : status === 401 || code === "UNAUTHORIZED" || code === "INVALID_SESSION_ID" ? "Unauthenticated" : status === 429 || code === "REQUEST_LIMIT_EXCEEDED" || name === "RateLimitReached" ? "RateLimited" : status === 403 || code === "PERMISSION_DENIED" || code === "INSUFFICIENT_ACCESS_OR_READONLY" ? "Forbidden" : status === 404 || code === "NOT_FOUND" ? "NotFound" : name === "FunctionEncounteredUserFacingError" || name === "QueryEncounteredUserFacingError" ? "ValidationFailed" : code === "FIELD_CUSTOM_VALIDATION_EXCEPTION" || code === "REQUIRED_FIELD_MISSING" ? "ValidationFailed" : status === 400 || code === "INVALID_ARGUMENT" ? "InvalidRequest" : status === 409 ? "Conflict" : "Unavailable";
179
+ const issues = (name === "FunctionEncounteredUserFacingError" || name === "QueryEncounteredUserFacingError") && Predicate.isString(value?.parameters?.message) ? [{
180
+ message: value.parameters.message,
181
+ code: "custom",
182
+ category: "custom",
183
+ source: "user-facing",
184
+ messageSource: "configured"
185
+ }] : void 0;
186
+ const seconds = value?.response?.headers?.["retry-after"];
187
+ return new BackendError({
188
+ operation,
189
+ kind,
190
+ retryAfterMs: value?.retryAfterMs ?? (seconds !== void 0 && /^\d+(?:\.\d+)?$/.test(seconds) ? Number(seconds) * 1e3 : void 0),
191
+ message: {
192
+ Unauthenticated: "Authentication is required.",
193
+ Forbidden: "This operation is not permitted.",
194
+ NotFound: "Resource not found.",
195
+ ValidationFailed: "Submission failed validation.",
196
+ InvalidRequest: "The request is invalid.",
197
+ InvalidResponse: "The source returned an invalid response.",
198
+ InvalidConfiguration: "The service is configured incorrectly.",
199
+ Conflict: "The operation conflicts with current state.",
200
+ NotImplemented: "This operation is not implemented.",
201
+ RateLimited: "Too many requests. Try again later.",
202
+ Unavailable: "The service is unavailable. Try again later.",
203
+ Internal: "The operation could not be completed."
204
+ }[kind],
205
+ retryable: kind === "Unavailable" || kind === "RateLimited",
206
+ actionOutcome: kind === "Unavailable" ? "unknown" : "not-committed",
207
+ issues,
208
+ cause: Redacted.make(cause)
209
+ });
210
+ }
211
+ function projectValidationIssue(issue, context) {
212
+ const parameter = issue.path?.[0];
213
+ if (!Predicate.isString(parameter) || !context.parameters?.includes(parameter)) return void 0;
214
+ if (issue.category === "input") {
215
+ const message = issue.messageSource === "standard" ? issue.message : {
216
+ required: "A value is required.",
217
+ type: "Enter a valid value.",
218
+ range: "Enter a value in the allowed range.",
219
+ arraySize: "Choose an allowed number of items.",
220
+ stringLength: "Enter a value of the allowed length.",
221
+ regex: "Enter a value in the required format."
222
+ }[issue.code ?? ""];
223
+ if (message) return {
224
+ message,
225
+ path: issue.path,
226
+ code: issue.code,
227
+ category: "input",
228
+ messageSource: "standard"
229
+ };
230
+ }
231
+ if (issue.code === "InvalidObjectReference") return {
232
+ message: "Choose a valid value.",
233
+ path: issue.path,
234
+ code: "InvalidObjectReference"
235
+ };
236
+ }
237
+ /** Forwarding preserves the original error. Projection removes raw causes and
238
+ * cannot change execution/retry facts. */
239
+ function projectBackendError(error, policy = "projected", context = {}) {
240
+ if (policy === "forward") return error;
241
+ const shown = typeof policy === "function" ? policy(error, context) : error;
242
+ const kind = error.kind === "Unauthenticated" && context.upstream ? "Unavailable" : shown.kind;
243
+ const issues = shown.kind !== "ValidationFailed" ? void 0 : policy === "projected" ? error.issues?.flatMap((issue) => {
244
+ const visible = projectValidationIssue(issue, context);
245
+ return visible ? [visible] : [];
246
+ }) : shown.issues;
247
+ const message = policy !== "projected" ? shown.message : kind === "ValidationFailed" ? "Submission failed validation." : kind === "InvalidRequest" ? "The request is invalid." : kind === "InvalidResponse" ? "The source returned an invalid response." : kind === "Unauthenticated" ? "Authentication is required." : kind === "Forbidden" ? "This operation is not permitted." : kind === "NotFound" ? "Resource not found." : kind === "RateLimited" ? "Too many requests. Try again later." : kind === "NotImplemented" ? "This operation is not implemented." : "The operation could not be completed.";
248
+ return new BackendError({
249
+ operation: error.operation,
250
+ kind,
251
+ message,
252
+ issues: issues?.length ? issues : void 0,
253
+ retryable: error.retryable,
254
+ actionOutcome: error.actionOutcome,
255
+ retryAfterMs: error.retryAfterMs
256
+ });
257
+ }
258
+ /** Schema diagnostics retain paths without echoing input values or internal schemas. */
259
+ function schemaValidationIssues(error) {
260
+ return SchemaIssue.makeFormatterStandardSchemaV1({
261
+ leafHook: (issue) => issue._tag === "MissingKey" ? "A value is required." : "Enter a valid value.",
262
+ checkHook: () => "Enter a valid value."
263
+ })(error.issue).issues.map((issue) => ({
264
+ message: issue.message,
265
+ path: issue.path?.flatMap((part) => typeof part === "string" || typeof part === "number" ? [part] : []),
266
+ category: "input",
267
+ code: issue.message === "A value is required." ? "required" : "type",
268
+ source: "parameter",
269
+ messageSource: "standard"
270
+ }));
271
+ }
272
+ //#endregion
273
+ export { BackendError, BackendErrorKindSchema, ValidationIssueSchema, ValidationReportSchema, backendErrorStatus, classifyBackendFailure, isUnauthenticatedError, isUnknownActionOutcome, projectBackendError, projectValidationIssue, schemaValidationIssues, unauthenticated };
274
+
275
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { OntologyStorageError } from \"@party-stack/ontology-storage\";\nimport { BlobStorageError } from \"@party-stack/ontology-storage/blobs\";\nimport { Predicate, Schema, SchemaIssue, Redacted } from \"effect\";\nimport { HttpClientError } from \"effect/http\";\nimport { RpcClientError } from \"effect/rpc\";\nimport type { ValidationIssue } from \"@party-stack/ontology-spec\";\n\nexport type { ValidationIssue };\nexport const ValidationIssueSchema = Schema.Struct({\n message: Schema.String,\n path: Schema.optional(Schema.Array(Schema.Union([Schema.String, Schema.Number]))),\n code: Schema.optional(Schema.String),\n category: Schema.optional(Schema.Literals([\"input\", \"reference\", \"custom\"])),\n source: Schema.optional(Schema.Literals([\"parameter\", \"submission\", \"user-facing\"])),\n messageSource: Schema.optional(Schema.Literals([\"standard\", \"configured\"])),\n});\nexport const ValidationReportSchema = Schema.Union([\n Schema.Struct({ certain: Schema.Literal(false) }),\n Schema.Struct({\n certain: Schema.Literal(true),\n value: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"ok\"), value: Schema.Void }),\n Schema.Struct({ kind: Schema.Literal(\"err\"), value: Schema.Array(ValidationIssueSchema) }),\n ]),\n }),\n]);\nexport type ValidationReport = typeof ValidationReportSchema.Type;\n\nexport const BackendErrorKindSchema = Schema.Literals([\n \"Unauthenticated\",\n \"Forbidden\",\n \"NotFound\",\n \"ValidationFailed\",\n \"InvalidRequest\",\n \"InvalidResponse\",\n \"InvalidConfiguration\",\n \"Conflict\",\n \"NotImplemented\",\n \"RateLimited\",\n \"Unavailable\",\n \"Internal\",\n \"HistoryExpired\",\n \"SessionExpired\",\n \"SessionReplaced\",\n \"ViewReplaced\",\n \"ResultExpired\",\n \"SourceMismatch\",\n \"SchemaMismatch\",\n]);\nexport type BackendErrorKind = typeof BackendErrorKindSchema.Type;\nconst Fields = {\n operation: Schema.String,\n kind: BackendErrorKindSchema,\n message: Schema.String,\n retryable: Schema.Boolean,\n actionOutcome: Schema.optional(Schema.Literals([\"not-committed\", \"unknown\"])),\n retryAfterMs: Schema.optional(Schema.Finite),\n issues: Schema.optional(Schema.Array(ValidationIssueSchema)),\n cause: Schema.optional(Schema.Defect()),\n};\n/** Shared wire schema; hooks narrow the kind without duplicating error classes. */\nexport class BackendError<\n K extends BackendErrorKind = BackendErrorKind,\n> extends Schema.TaggedError<BackendError>()(\"BackendError\", Fields) {\n declare readonly kind: K;\n constructor(properties: Omit<Schema.Struct.Type<typeof Fields>, \"kind\"> & { readonly kind: K }) {\n super(properties);\n }\n}\n/** HTTP bindings share these statuses; RPC still carries the typed error schema. */\nexport const backendErrorStatus = (error: Pick<BackendError, \"kind\">): number =>\n ({\n Unauthenticated: 401,\n Forbidden: 403,\n NotFound: 404,\n ValidationFailed: 422,\n InvalidRequest: 400,\n InvalidResponse: 502,\n InvalidConfiguration: 500,\n Conflict: 409,\n NotImplemented: 501,\n RateLimited: 429,\n Unavailable: 503,\n Internal: 500,\n HistoryExpired: 409,\n SessionExpired: 409,\n SessionReplaced: 409,\n ViewReplaced: 409,\n ResultExpired: 409,\n SourceMismatch: 409,\n SchemaMismatch: 409,\n })[error.kind];\nexport type OperationErrorKind =\n | \"Unauthenticated\"\n | \"Forbidden\"\n | \"NotFound\"\n | \"ValidationFailed\"\n | \"InvalidRequest\"\n | \"InvalidResponse\"\n | \"InvalidConfiguration\"\n | \"Conflict\"\n | \"NotImplemented\"\n | \"RateLimited\"\n | \"Unavailable\"\n | \"Internal\";\nexport type ApplyActionError = BackendError<OperationErrorKind>;\nexport type ValidateActionError = BackendError<OperationErrorKind>;\nexport type ReplicationErrorKind =\n | \"HistoryExpired\"\n | \"SessionExpired\"\n | \"SessionReplaced\"\n | \"ViewReplaced\"\n | \"ResultExpired\"\n | \"SourceMismatch\"\n | \"SchemaMismatch\";\nexport type ReplicationError = BackendError<ReplicationErrorKind>;\nexport type LoadSubsetError = BackendError<\n Exclude<OperationErrorKind, \"ValidationFailed\"> | \"HistoryExpired\"\n>;\n\nexport const unauthenticated = (message = \"Authentication is required.\", options?: ErrorOptions) =>\n new BackendError({\n operation: \"authentication\",\n kind: \"Unauthenticated\",\n message,\n retryable: false,\n actionOutcome: \"not-committed\",\n cause: options?.cause,\n });\nexport const isUnauthenticatedError = (error: unknown): error is BackendError<\"Unauthenticated\"> =>\n error instanceof BackendError && error.kind === \"Unauthenticated\";\n\n/** Unknown outcomes apply to dispatch/execution failures, never ordinary rejections. */\nexport const isUnknownActionOutcome = (error: BackendError) =>\n error.actionOutcome === \"unknown\" ||\n (error.actionOutcome === undefined &&\n (error.kind === \"Unavailable\" || error.kind === \"Internal\" || error.kind === \"InvalidResponse\"));\n\nconst ProviderFailure = Schema.Struct({\n reason: Schema.optional(Schema.Unknown),\n cause: Schema.optional(Schema.Unknown),\n response: Schema.optional(\n Schema.Struct({\n status: Schema.Number,\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n })\n ),\n retryAfterMs: Schema.optional(Schema.Finite),\n status: Schema.optional(Schema.Number),\n statusCode: Schema.optional(Schema.Number),\n errorCode: Schema.optional(Schema.String),\n errorName: Schema.optional(Schema.String),\n code: Schema.optional(Schema.String),\n parameters: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),\n});\n/** Normalize SDK failures. No provider message/body is made public by this classifier. */\nexport function classifyBackendFailure(operation: string, cause: unknown): BackendError {\n if (cause instanceof BackendError) return cause;\n // Effect RPC currently puts HTTP EOF in RpcClientDefect alongside decoding\n // failures. Only its two explicit EOF cases mean transport loss; malformed\n // frames must remain terminal InvalidResponse failures. Replace this narrow\n // normalization when upstream exposes a structured interrupted-response reason.\n if (\n cause instanceof RpcClientError.RpcClientError &&\n cause.reason._tag === \"RpcClientDefect\" &&\n (cause.reason.message === \"HTTP response ended before RPC request completed\" ||\n cause.reason.message === \"Received empty HTTP response from RPC server\")\n )\n return new BackendError({\n operation,\n kind: \"Unavailable\",\n message: \"The RPC connection was interrupted.\",\n retryable: true,\n actionOutcome: \"unknown\",\n cause: Redacted.make(cause),\n });\n if (\n (cause instanceof RpcClientError.RpcClientError && cause.reason._tag === \"RpcClientDefect\") ||\n (cause instanceof HttpClientError.HttpClientError && cause.reason._tag === \"DecodeError\")\n )\n return new BackendError({\n operation,\n kind: \"InvalidResponse\",\n message: \"The source returned an invalid response.\",\n retryable: false,\n actionOutcome: \"unknown\",\n cause: Redacted.make(cause),\n });\n if (\n cause instanceof HttpClientError.HttpClientError &&\n (cause.reason._tag === \"EncodeError\" || cause.reason._tag === \"InvalidUrlError\")\n )\n return new BackendError({\n operation,\n kind: cause.reason._tag === \"EncodeError\" ? \"InvalidRequest\" : \"InvalidConfiguration\",\n message: \"The request could not be constructed.\",\n retryable: false,\n actionOutcome: \"not-committed\",\n cause: Redacted.make(cause),\n });\n const blob =\n cause instanceof BlobStorageError\n ? cause\n : cause instanceof OntologyStorageError && cause.reason._tag === \"BlobStorageError\"\n ? cause.reason\n : undefined;\n if (blob) {\n return new BackendError({\n operation,\n kind:\n blob.kind === \"NotFound\"\n ? \"NotFound\"\n : blob.kind === \"InvalidValue\"\n ? \"InvalidRequest\"\n : blob.kind === \"Busy\" || blob.kind === \"Conflict\"\n ? \"Conflict\"\n : \"Unavailable\",\n message:\n blob.kind === \"NotFound\"\n ? \"Attachment is unavailable.\"\n : blob.kind === \"Busy\"\n ? \"Attachment upload is still in progress.\"\n : blob.kind === \"Conflict\"\n ? \"Attachment state conflicts with this operation.\"\n : blob.kind === \"InvalidValue\"\n ? \"Invalid attachment value.\"\n : \"Attachment storage is unavailable.\",\n retryable: blob.kind === \"Busy\" || blob.kind === \"Bytes\",\n cause: Redacted.make(cause),\n });\n }\n if (cause instanceof OntologyStorageError) {\n const reason = cause.reason;\n const kind: BackendErrorKind =\n reason._tag === \"QueryError\"\n ? \"InvalidRequest\"\n : reason._tag === \"ConfigurationError\" || reason._tag === \"IndexError\"\n ? \"InvalidConfiguration\"\n : reason._tag === \"DefinitionMismatch\" || reason._tag === \"SchemaMismatch\"\n ? \"SchemaMismatch\"\n : reason._tag === \"UniqueConstraint\"\n ? \"Conflict\"\n : reason._tag === \"StorageError\" ||\n (reason._tag === \"TransactionError\" && reason.kind === \"Backend\")\n ? \"Unavailable\"\n : \"Internal\";\n return new BackendError({\n operation,\n kind,\n message:\n kind === \"InvalidRequest\"\n ? \"Invalid storage query.\"\n : kind === \"SchemaMismatch\"\n ? \"Storage schema changed; migrate or reset explicitly.\"\n : \"Storage operation failed.\",\n retryable: cause.isRetryable,\n cause: Redacted.make(cause),\n });\n }\n let candidate = cause;\n let value: typeof ProviderFailure.Type | undefined;\n for (let depth = 0; depth < 5; depth++) {\n if (candidate instanceof BackendError) return candidate;\n const decoded = Schema.decodeUnknownOption(ProviderFailure)(candidate);\n if (decoded._tag === \"None\") break;\n value = decoded.value;\n if (value.cause instanceof BackendError) return value.cause;\n if (\n value.status !== undefined ||\n value.statusCode !== undefined ||\n value.errorCode !== undefined ||\n value.code !== undefined ||\n value.errorName !== undefined ||\n value.response\n )\n break;\n candidate = value.reason ?? value.cause;\n }\n const status = value?.status ?? value?.statusCode ?? value?.response?.status;\n const code = value?.errorCode ?? value?.code;\n const name = value?.errorName?.split(\":\").at(-1);\n const kind: OperationErrorKind =\n status === 501\n ? \"NotImplemented\"\n : status === 401 || code === \"UNAUTHORIZED\" || code === \"INVALID_SESSION_ID\"\n ? \"Unauthenticated\"\n : status === 429 || code === \"REQUEST_LIMIT_EXCEEDED\" || name === \"RateLimitReached\"\n ? \"RateLimited\"\n : status === 403 || code === \"PERMISSION_DENIED\" || code === \"INSUFFICIENT_ACCESS_OR_READONLY\"\n ? \"Forbidden\"\n : status === 404 || code === \"NOT_FOUND\"\n ? \"NotFound\"\n : name === \"FunctionEncounteredUserFacingError\" ||\n name === \"QueryEncounteredUserFacingError\"\n ? \"ValidationFailed\"\n : code === \"FIELD_CUSTOM_VALIDATION_EXCEPTION\" || code === \"REQUIRED_FIELD_MISSING\"\n ? \"ValidationFailed\"\n : status === 400 || code === \"INVALID_ARGUMENT\"\n ? \"InvalidRequest\"\n : status === 409\n ? \"Conflict\"\n : \"Unavailable\";\n const authored =\n name === \"FunctionEncounteredUserFacingError\" || name === \"QueryEncounteredUserFacingError\";\n const issues: readonly ValidationIssue[] | undefined =\n authored && Predicate.isString(value?.parameters?.message)\n ? [\n {\n message: value.parameters.message,\n code: \"custom\",\n category: \"custom\",\n source: \"user-facing\",\n messageSource: \"configured\",\n },\n ]\n : undefined;\n const seconds = value?.response?.headers?.[\"retry-after\"];\n const retryAfterMs =\n value?.retryAfterMs ??\n (seconds !== undefined && /^\\d+(?:\\.\\d+)?$/.test(seconds) ? Number(seconds) * 1_000 : undefined);\n return new BackendError({\n operation,\n kind,\n retryAfterMs,\n message: {\n Unauthenticated: \"Authentication is required.\",\n Forbidden: \"This operation is not permitted.\",\n NotFound: \"Resource not found.\",\n ValidationFailed: \"Submission failed validation.\",\n InvalidRequest: \"The request is invalid.\",\n InvalidResponse: \"The source returned an invalid response.\",\n InvalidConfiguration: \"The service is configured incorrectly.\",\n Conflict: \"The operation conflicts with current state.\",\n NotImplemented: \"This operation is not implemented.\",\n RateLimited: \"Too many requests. Try again later.\",\n Unavailable: \"The service is unavailable. Try again later.\",\n Internal: \"The operation could not be completed.\",\n }[kind],\n retryable: kind === \"Unavailable\" || kind === \"RateLimited\",\n actionOutcome: kind === \"Unavailable\" ? \"unknown\" : \"not-committed\",\n issues,\n cause: Redacted.make(cause),\n });\n}\n\nexport interface ErrorProjectionContext {\n /** Visible action parameter paths. Hidden/fixed parameters must not appear in public issues. */\n readonly parameters?: readonly string[];\n readonly objectReferenceParameters?: readonly string[];\n /** An upstream connection failure cannot request downstream sign-in. */\n readonly upstream?: boolean;\n}\nexport type ErrorProjection =\n | \"forward\"\n | \"projected\"\n | ((error: BackendError, context: ErrorProjectionContext) => BackendError);\nexport function projectValidationIssue(\n issue: ValidationIssue,\n context: ErrorProjectionContext\n): ValidationIssue | undefined {\n const parameter = issue.path?.[0];\n if (!Predicate.isString(parameter) || !context.parameters?.includes(parameter)) return undefined;\n if (issue.category === \"input\") {\n const standard: Readonly<Record<string, string>> = {\n required: \"A value is required.\",\n type: \"Enter a valid value.\",\n range: \"Enter a value in the allowed range.\",\n arraySize: \"Choose an allowed number of items.\",\n stringLength: \"Enter a value of the allowed length.\",\n regex: \"Enter a value in the required format.\",\n };\n const message = issue.messageSource === \"standard\" ? issue.message : standard[issue.code ?? \"\"];\n if (message)\n return {\n message,\n path: issue.path,\n code: issue.code,\n category: \"input\",\n messageSource: \"standard\",\n };\n }\n if (issue.code === \"InvalidObjectReference\")\n return { message: \"Choose a valid value.\", path: issue.path, code: \"InvalidObjectReference\" };\n return undefined;\n}\n/** Forwarding preserves the original error. Projection removes raw causes and\n * cannot change execution/retry facts. */\nexport function projectBackendError(\n error: BackendError,\n policy: ErrorProjection = \"projected\",\n context: ErrorProjectionContext = {}\n): BackendError {\n if (policy === \"forward\") return error;\n const shown = typeof policy === \"function\" ? policy(error, context) : error;\n const kind = error.kind === \"Unauthenticated\" && context.upstream ? \"Unavailable\" : shown.kind;\n const issues =\n shown.kind !== \"ValidationFailed\"\n ? undefined\n : policy === \"projected\"\n ? error.issues?.flatMap((issue) => {\n const visible = projectValidationIssue(issue, context);\n return visible ? [visible] : [];\n })\n : shown.issues;\n const message =\n policy !== \"projected\"\n ? shown.message\n : kind === \"ValidationFailed\"\n ? \"Submission failed validation.\"\n : kind === \"InvalidRequest\"\n ? \"The request is invalid.\"\n : kind === \"InvalidResponse\"\n ? \"The source returned an invalid response.\"\n : kind === \"Unauthenticated\"\n ? \"Authentication is required.\"\n : kind === \"Forbidden\"\n ? \"This operation is not permitted.\"\n : kind === \"NotFound\"\n ? \"Resource not found.\"\n : kind === \"RateLimited\"\n ? \"Too many requests. Try again later.\"\n : kind === \"NotImplemented\"\n ? \"This operation is not implemented.\"\n : \"The operation could not be completed.\";\n return new BackendError({\n operation: error.operation,\n kind,\n message,\n issues: issues?.length ? issues : undefined,\n retryable: error.retryable,\n actionOutcome: error.actionOutcome,\n retryAfterMs: error.retryAfterMs,\n });\n}\nexport type UnauthenticatedError = BackendError<\"Unauthenticated\">;\n\n/** Schema diagnostics retain paths without echoing input values or internal schemas. */\nexport function schemaValidationIssues(error: Schema.SchemaError): readonly ValidationIssue[] {\n return SchemaIssue.makeFormatterStandardSchemaV1({\n leafHook: (issue) => (issue._tag === \"MissingKey\" ? \"A value is required.\" : \"Enter a valid value.\"),\n checkHook: () => \"Enter a valid value.\",\n })(error.issue).issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.flatMap((part) =>\n typeof part === \"string\" || typeof part === \"number\" ? [part] : []\n ),\n category: \"input\",\n code: issue.message === \"A value is required.\" ? \"required\" : \"type\",\n source: \"parameter\",\n messageSource: \"standard\",\n }));\n}\n"],"mappings":";;;;;;AAQA,MAAa,wBAAwB,OAAO,OAAO;CAC/C,SAAS,OAAO;CAChB,MAAM,OAAO,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC,CAAC,CAAC;CAChF,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,UAAU,OAAO,SAAS,OAAO,SAAS;EAAC;EAAS;EAAa;CAAQ,CAAC,CAAC;CAC3E,QAAQ,OAAO,SAAS,OAAO,SAAS;EAAC;EAAa;EAAc;CAAa,CAAC,CAAC;C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ACrD,OAAO,UAAU,CAAC,OAAO,IAAI,CAAC;CAClC,CAAC,IACD,MAAM;CAClB,MAAM,UACF,WAAW,cACL,MAAM,UACN,SAAS,qBACP,kCACA,SAAS,mBACP,4BACA,SAAS,oBACP,6CACA,SAAS,oBACP,gCACA,SAAS,cACP,qCACA,SAAS,aACP,wBACA,SAAS,gBACP,wCACA,SAAS,mBACP,uCACA;CAC1B,OAAO,IAAI,aAAa;EACpB,WAAW,MAAM;EACjB;EACA;EACA,QAAQ,QAAQ,SAAS,SAAS,KAAA;EAClC,WAAW,MAAM;EACjB,eAAe,MAAM;EACrB,cAAc,MAAM;CACxB,CAAC;AACL;;AAIA,SAAgB,uBAAuB,OAAuD;CAC1F,OAAO,YAAY,8BAA8B;EAC7C,WAAW,UAAW,MAAM,SAAS,eAAe,yBAAyB;EAC7E,iBAAiB;CACrB,CAAC,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,OAAO,KAAK,WAAW;EACnC,SAAS,MAAM;EACf,MAAM,MAAM,MAAM,SAAS,SACvB,OAAO,SAAS,YAAY,OAAO,SAAS,WAAW,CAAC,IAAI,IAAI,CAAC,CACrE;EACA,UAAU;EACV,MAAM,MAAM,YAAY,yBAAyB,aAAa;EAC9D,QAAQ;EACR,eAAe;CACnB,EAAE;AACN"}
@@ -0,0 +1,25 @@
1
+ import { BackendError } from "./errors.js";
2
+ import { BackendSnapshot, SourceQueryPlan } from "./index.js";
3
+ import { CompiledSubset } from "./subset.js";
4
+ import { ObjectSubset } from "@party-stack/ontology-spec/query";
5
+ import { Effect } from "effect";
6
+ import { OntologyIR } from "@party-stack/ontology-spec";
7
+ //#region src/fulfillment.d.ts
8
+ /** A windowed source can supply a wider prefix of the same ordered/filtered result. */
9
+ export declare function coversSubset(request: CompiledSubset, fulfilled: CompiledSubset): boolean;
10
+ /** Normalize exactly once at a consumer boundary; provider windows must not be applied twice. */
11
+ export declare const resolveSubsetSnapshot: (ir: OntologyIR, request: ObjectSubset, snapshot: BackendSnapshot, context?: Record<string, unknown> | undefined) => Effect.Effect<{
12
+ requested: CompiledSubset;
13
+ fulfilled: CompiledSubset;
14
+ fulfilledRows: import("@party-stack/ontology-storage").Row<Record<string, unknown>>[];
15
+ snapshot: {
16
+ complete: boolean;
17
+ fetchedRows?: number;
18
+ pushdown?: SourceQueryPlan;
19
+ cursor?: string;
20
+ fulfilledSubset: undefined;
21
+ rows: import("@party-stack/ontology-storage").Row<Record<string, unknown>>[];
22
+ };
23
+ }, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>;
24
+ //#endregion
25
+ //# sourceMappingURL=fulfillment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fulfillment.d.ts","names":["_$__index_js0.SourceQueryPlan"],"sources":["../src/fulfillment.ts"],"mappings":";;;;;;;;wBAwCgB,aAAa,SAAS,gBAAgB,WAAW;;qBAiBpD,wBAAqB,IAAA,YAAA,SAAA,cAAA,UAAA,iBAAA,UAAA,wCAAA,OAAA;;;;;;;;;;;;GAoEhC"}
@@ -0,0 +1,99 @@
1
+ import { BackendError } from "./errors.js";
2
+ import { BackendSnapshotSchema } from "./index.js";
3
+ import { compileObjectSubset } from "./subset.js";
4
+ import { evaluateQuery } from "@party-stack/ontology-storage";
5
+ import { Effect, Redacted, Schema } from "effect";
6
+ import { Table, isField } from "@party-stack/ontology-storage/tables";
7
+ //#region src/fulfillment.ts
8
+ const codec = Table.make({ name: "subset-fulfillment" });
9
+ const same = (left, right) => codec.encode(left) === codec.encode(right);
10
+ const windowed = (query) => query.limit !== void 0 || Boolean(query.offset) || query.after !== void 0;
11
+ /** Sound, deliberately small implication rules for declared coverage; no data-dependent inference. */
12
+ function implies(request, fulfilled) {
13
+ if (!fulfilled) return true;
14
+ if (!request) return false;
15
+ if (same(request, fulfilled)) return true;
16
+ if (request.op === "or") return request.predicates.every((child) => implies(child, fulfilled));
17
+ if (fulfilled.op === "and") return fulfilled.predicates.every((child) => implies(request, child));
18
+ if (request.op === "and" && request.predicates.some((child) => implies(child, fulfilled))) return true;
19
+ if (fulfilled.op === "or" && fulfilled.predicates.some((child) => implies(request, child))) return true;
20
+ if (fulfilled.op === "in") {
21
+ if (request.op === "in" && same(request.left, fulfilled.left)) return request.values.every((value) => fulfilled.values.some((other) => same(value, other)));
22
+ if (request.op === "eq") {
23
+ const field = isField(request.left) ? request.left : request.right;
24
+ const value = field === request.left ? request.right : request.left;
25
+ if (isField(field) && !isField(value) && same(field, fulfilled.left)) return fulfilled.values.some((other) => same(value, other));
26
+ }
27
+ }
28
+ return false;
29
+ }
30
+ /** A windowed source can supply a wider prefix of the same ordered/filtered result. */
31
+ function coversSubset(request, fulfilled) {
32
+ if (request.objectType !== fulfilled.objectType) return false;
33
+ const wanted = request.query ?? {}, actual = fulfilled.query ?? {};
34
+ if (!windowed(actual)) return implies(wanted.where, actual.where);
35
+ if (!same(wanted.where, actual.where) || !same(wanted.orderBy ?? [], actual.orderBy ?? []) || !same(wanted.after, actual.after)) return false;
36
+ const delta = (wanted.offset ?? 0) - (actual.offset ?? 0);
37
+ if (delta < 0) return false;
38
+ return actual.limit === void 0 || wanted.limit !== void 0 && delta + wanted.limit <= actual.limit;
39
+ }
40
+ /** Normalize exactly once at a consumer boundary; provider windows must not be applied twice. */
41
+ const resolveSubsetSnapshot = Effect.fnUntraced(function* (ir, request, snapshot, context) {
42
+ snapshot = yield* Schema.decodeUnknownEffect(BackendSnapshotSchema)(snapshot).pipe(Effect.mapError((cause) => new BackendError({
43
+ operation: "loadSubset",
44
+ kind: "InvalidResponse",
45
+ message: "The provider returned an invalid snapshot.",
46
+ retryable: false,
47
+ cause: Redacted.make(cause)
48
+ })));
49
+ const requested = yield* compileObjectSubset(ir, request, context);
50
+ const fulfilled = snapshot.fulfilledSubset ? yield* compileObjectSubset(ir, snapshot.fulfilledSubset, context).pipe(Effect.mapError((cause) => new BackendError({
51
+ operation: "loadSubset",
52
+ kind: "InvalidResponse",
53
+ message: "The provider reported an invalid fulfilled subset.",
54
+ retryable: false,
55
+ cause: Redacted.make(cause)
56
+ }))) : requested;
57
+ return yield* Effect.try({
58
+ try: () => {
59
+ if (!coversSubset(requested, fulfilled)) throw new Error("The fulfilled subset does not cover the request.");
60
+ const primaryKey = ir.objectTypes.find((type) => type.name === requested.objectType).primaryKey;
61
+ const keys = /* @__PURE__ */ new Set();
62
+ for (const row of snapshot.rows) {
63
+ if (row.value[primaryKey] !== row.key || keys.has(row.key)) throw new Error("Invalid or duplicate snapshot identity.");
64
+ keys.add(row.key);
65
+ }
66
+ const query = requested.query ?? {};
67
+ const actual = fulfilled.query ?? {};
68
+ const requestedQuery = {
69
+ ...query,
70
+ offset: Math.max(0, (query.offset ?? 0) - (actual.offset ?? 0))
71
+ };
72
+ const rows = evaluateQuery(snapshot.rows, requestedQuery);
73
+ return {
74
+ requested,
75
+ fulfilled,
76
+ fulfilledRows: evaluateQuery(snapshot.rows, {
77
+ ...actual,
78
+ offset: 0
79
+ }),
80
+ snapshot: {
81
+ ...snapshot,
82
+ fulfilledSubset: void 0,
83
+ rows
84
+ }
85
+ };
86
+ },
87
+ catch: (cause) => new BackendError({
88
+ operation: "loadSubset",
89
+ kind: "InvalidResponse",
90
+ retryable: false,
91
+ message: "The provider returned an incompatible subset snapshot.",
92
+ cause: Redacted.make(cause)
93
+ })
94
+ });
95
+ });
96
+ //#endregion
97
+ export { coversSubset, resolveSubsetSnapshot };
98
+
99
+ //# sourceMappingURL=fulfillment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fulfillment.js","names":[],"sources":["../src/fulfillment.ts"],"sourcesContent":["import { evaluateQuery } from \"@party-stack/ontology-storage\";\nimport { Table, isField } from \"@party-stack/ontology-storage/tables\";\nimport { Effect, Redacted, Schema } from \"effect\";\nimport { BackendError } from \"./errors.js\";\nimport { compileObjectSubset } from \"./subset.js\";\nimport { BackendSnapshotSchema } from \"./index.js\";\nimport type { BackendSnapshot } from \"./index.js\";\nimport type { CompiledSubset } from \"./subset.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { Predicate, Query } from \"@party-stack/ontology-storage\";\n\nconst codec = Table.make<unknown>({ name: \"subset-fulfillment\" });\nconst same = (left: unknown, right: unknown) => codec.encode(left) === codec.encode(right);\nconst windowed = (query: Query) =>\n query.limit !== undefined || Boolean(query.offset) || query.after !== undefined;\n\n/** Sound, deliberately small implication rules for declared coverage; no data-dependent inference. */\nfunction implies(request: Predicate | undefined, fulfilled: Predicate | undefined): boolean {\n if (!fulfilled) return true;\n if (!request) return false;\n if (same(request, fulfilled)) return true;\n if (request.op === \"or\") return request.predicates.every((child) => implies(child, fulfilled));\n if (fulfilled.op === \"and\") return fulfilled.predicates.every((child) => implies(request, child));\n if (request.op === \"and\" && request.predicates.some((child) => implies(child, fulfilled))) return true;\n if (fulfilled.op === \"or\" && fulfilled.predicates.some((child) => implies(request, child))) return true;\n if (fulfilled.op === \"in\") {\n if (request.op === \"in\" && same(request.left, fulfilled.left))\n return request.values.every((value) => fulfilled.values.some((other) => same(value, other)));\n if (request.op === \"eq\") {\n const field = isField(request.left) ? request.left : request.right;\n const value = field === request.left ? request.right : request.left;\n if (isField(field) && !isField(value) && same(field, fulfilled.left))\n return fulfilled.values.some((other) => same(value, other));\n }\n }\n return false;\n}\n\n/** A windowed source can supply a wider prefix of the same ordered/filtered result. */\nexport function coversSubset(request: CompiledSubset, fulfilled: CompiledSubset): boolean {\n if (request.objectType !== fulfilled.objectType) return false;\n const wanted = request.query ?? {},\n actual = fulfilled.query ?? {};\n if (!windowed(actual)) return implies(wanted.where, actual.where);\n if (\n !same(wanted.where, actual.where) ||\n !same(wanted.orderBy ?? [], actual.orderBy ?? []) ||\n !same(wanted.after, actual.after)\n )\n return false;\n const delta = (wanted.offset ?? 0) - (actual.offset ?? 0);\n if (delta < 0) return false;\n return actual.limit === undefined || (wanted.limit !== undefined && delta + wanted.limit <= actual.limit);\n}\n\n/** Normalize exactly once at a consumer boundary; provider windows must not be applied twice. */\nexport const resolveSubsetSnapshot = Effect.fnUntraced(function* (\n ir: OntologyIR,\n request: ObjectSubset,\n snapshot: BackendSnapshot,\n context?: Record<string, unknown>\n) {\n snapshot = yield* Schema.decodeUnknownEffect(BackendSnapshotSchema)(snapshot).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider returned an invalid snapshot.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n );\n const requested = yield* compileObjectSubset(ir, request, context);\n const fulfilled = snapshot.fulfilledSubset\n ? yield* compileObjectSubset(ir, snapshot.fulfilledSubset, context).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider reported an invalid fulfilled subset.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n )\n : requested;\n return yield* Effect.try({\n try: () => {\n if (!coversSubset(requested, fulfilled))\n throw new Error(\"The fulfilled subset does not cover the request.\");\n const primaryKey = ir.objectTypes.find((type) => type.name === requested.objectType)!.primaryKey;\n const keys = new Set<string | number>();\n for (const row of snapshot.rows) {\n if (row.value[primaryKey] !== row.key || keys.has(row.key))\n throw new Error(\"Invalid or duplicate snapshot identity.\");\n keys.add(row.key);\n }\n const query = requested.query ?? {};\n const actual = fulfilled.query ?? {};\n // Rows from an explicitly fulfilled window have already skipped its offset.\n const requestedQuery = {\n ...query,\n offset: Math.max(0, (query.offset ?? 0) - (actual.offset ?? 0)),\n };\n const rows = evaluateQuery(snapshot.rows, requestedQuery);\n return {\n requested,\n fulfilled,\n fulfilledRows: evaluateQuery(snapshot.rows, { ...actual, offset: 0 }),\n snapshot: { ...snapshot, fulfilledSubset: undefined, rows },\n };\n },\n catch: (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"The provider returned an incompatible subset snapshot.\",\n cause: Redacted.make(cause),\n }),\n });\n});\n"],"mappings":";;;;;;;AAYA,MAAM,QAAQ,MAAM,KAAc,EAAE,MAAM,qBAAqB,CAAC;AAChE,MAAM,QAAQ,MAAe,UAAmB,MAAM,OAAO,IAAI,MAAM,MAAM,OAAO,KAAK;AACzF,MAAM,YAAY,UACd,MAAM,UAAU,KAAA,KAAa,QAAQ,MAAM,MAAM,KAAK,MAAM,UAAU,KAAA;;AAG1E,SAAS,QAAQ,SAAgC,WAA2C;CACxF,IAAI,CAAC,WAAW,OAAO;CACvB,IAAI,CAAC,SAAS,OAAO;CACrB,IAAI,KAAK,SAAS,SAAS,GAAG,OAAO;CACrC,IAAI,QAAQ,OAAO,MAAM,OAAO,QAAQ,WAAW,OAAO,UAAU,QAAQ,OAAO,SAAS,CAAC;CAC7F,IAAI,UAAU,OAAO,OAAO,OAAO,UAAU,WAAW,OAAO,UAAU,QAAQ,SAAS,KAAK,CAAC;CAChG,IAAI,QAAQ,OAAO,SAAS,QAAQ,WAAW,MAAM,UAAU,QAAQ,OAAO,SAAS,CAAC,GAAG,OAAO;CAClG,IAAI,UAAU,OAAO,QAAQ,UAAU,WAAW,MAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,GAAG,OAAO;CACnG,IAAI,UAAU,OAAO,MAAM;EACvB,IAAI,QAAQ,OAAO,QAAQ,KAAK,QAAQ,MAAM,UAAU,IAAI,GACxD,OAAO,QAAQ,OAAO,OAAO,UAAU,UAAU,OAAO,MAAM,UAAU,KAAK,OAAO,KAAK,CAAC,CAAC;EAC/F,IAAI,QAAQ,OAAO,MAAM;GACrB,MAAM,QAAQ,QAAQ,QAAQ,IAAI,IAAI,QAAQ,OAAO,QAAQ;GAC7D,MAAM,QAAQ,UAAU,QAAQ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