@powerhousedao/reactor-api 6.2.3-staging.0 → 6.3.0-dev.1

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 (57) hide show
  1. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +12 -14
  2. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  3. package/dist/{adapter-gateway-mercurius-rbKlwF9m.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  4. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  5. package/dist/{adapter-http-express-CWqziB1p.mjs → adapter-http-express-78KD77cI.mjs} +7 -7
  6. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  7. package/dist/{adapter-http-fastify-CYZQ6FFv.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +7 -7
  8. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  9. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  10. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  11. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  12. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  13. package/dist/error-info-Cr6oQACe.mjs +601 -0
  14. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  15. package/dist/index.d.mts +2944 -930
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +7111 -2845
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs.map +1 -0
  21. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  23. package/dist/pglite-node-CcX2YT-l.mjs +744 -0
  24. package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
  25. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  26. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  27. package/dist/src/graphql/subgraph-types.mjs +14 -0
  28. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  29. package/dist/src/packages/vite-loader.d.mts +13 -2
  30. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  31. package/dist/src/packages/vite-loader.mjs +122 -69
  32. package/dist/src/packages/vite-loader.mjs.map +1 -1
  33. package/dist/src/pglite/pglite-node.d.mts +434 -0
  34. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  35. package/dist/src/pglite/pglite-node.mjs +5 -0
  36. package/dist/src/pglite/worker/entry.d.mts +2 -0
  37. package/dist/src/pglite/worker/entry.mjs +298 -0
  38. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  39. package/dist/subgraph-extraction-uJ8BR0he.mjs +2020 -0
  40. package/dist/subgraph-extraction-uJ8BR0he.mjs.map +1 -0
  41. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  42. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  43. package/dist/{types-CuSz_zv6.d.mts → types-Bz_xjf8j.d.mts} +41 -7
  44. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  45. package/package.json +36 -23
  46. package/dist/adapter-gateway-apollo-B54G_cXT.mjs.map +0 -1
  47. package/dist/adapter-gateway-apollo-D2DNlPY0.mjs +0 -4
  48. package/dist/adapter-gateway-mercurius-rbKlwF9m.mjs.map +0 -1
  49. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs +0 -321
  50. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs.map +0 -1
  51. package/dist/adapter-http-express-CWqziB1p.mjs.map +0 -1
  52. package/dist/adapter-http-fastify-CYZQ6FFv.mjs.map +0 -1
  53. package/dist/pieces-swupjgIO.mjs +0 -790
  54. package/dist/pieces-swupjgIO.mjs.map +0 -1
  55. package/dist/types-CuSz_zv6.d.mts.map +0 -1
  56. package/dist/websocket-_SH5aBcy.mjs +0 -18
  57. package/dist/websocket-_SH5aBcy.mjs.map +0 -1
@@ -1,790 +0,0 @@
1
-
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0b933e15-7a73-537c-acf4-89127d6433f5")}catch(e){}}();
3
- import { createRequire } from "node:module";
4
- import { gql } from "graphql-tag";
5
- import { GraphQLError } from "graphql";
6
- import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
7
- import { childLogger } from "document-model";
8
- import path, { dirname, isAbsolute, join } from "node:path";
9
- import { existsSync, readFileSync } from "node:fs";
10
- import { fileURLToPath, pathToFileURL } from "node:url";
11
- import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
12
- //#region src/graphql/errors.ts
13
- /** Caller (authenticated or anonymous) lacks permission for the document. */
14
- var ForbiddenError = class extends GraphQLError {
15
- constructor(detail = "") {
16
- const base = DRIVE_AUTH_ERROR_MESSAGES.forbidden;
17
- super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "FORBIDDEN" } });
18
- }
19
- };
20
- /** Anonymous caller on an action that requires logging in. */
21
- var AuthenticationRequiredError = class extends GraphQLError {
22
- constructor(detail = "") {
23
- const base = DRIVE_AUTH_ERROR_MESSAGES.authenticationRequired;
24
- super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "UNAUTHENTICATED" } });
25
- }
26
- };
27
- /**
28
- * The reactor holds no decision model, so no authorization preflight can be
29
- * answered.
30
- *
31
- * Distinct from a denial, and deliberately so: a caller that cannot get a
32
- * prediction should render its controls as it did before it asked and let the
33
- * submit path refuse. Reading this as a denial would disable every control on a
34
- * switchboard running without authEnforcement. The code is what a client
35
- * branches on, since the message is not a contract.
36
- */
37
- var AuthEvaluationUnsupportedError = class extends GraphQLError {
38
- constructor() {
39
- super("Authorization evaluation is unavailable: this reactor runs without the authEnforcement feature flag, so it holds no decision model", { extensions: { code: "AUTH_EVALUATION_UNSUPPORTED" } });
40
- }
41
- };
42
- /**
43
- * A stored operation cannot be represented in the schema, so it is reported
44
- * rather than served.
45
- *
46
- * The schema declares an action's id, type, timestamp, input and scope
47
- * non-null; an operation written before the API rejected an action without an
48
- * id violates that. Left to the executor, the missing value nullifies the
49
- * action, which bubbles up through the non-null chain until it nullifies the
50
- * envelope's whole operation list, and the caller receives a partial response
51
- * beside "Cannot return null for non-nullable field Action.id" - which says
52
- * nothing about which operation, and which a sync client can only read as a
53
- * permanent GraphQL rejection, stopping its poll timer for good.
54
- *
55
- * Thrown instead, with a code that says the failure is worth polling through:
56
- * the document holding the operation needs repairing, but the channel serves
57
- * every other document, and a peer that stopped polling would stop receiving
58
- * those too. The code is what a client branches on, since the message is not a
59
- * contract.
60
- */
61
- var MalformedStoredOperationError = class extends GraphQLError {
62
- constructor(detail) {
63
- super(`Stored operation cannot be served: ${detail}`, { extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation } });
64
- }
65
- };
66
- //#endregion
67
- //#region src/services/authorization.service.ts
68
- /**
69
- * Result of a passed per-document authorization check. `fetchIdentifier` is
70
- * always safe for the data fetch: the canonical id when resolved, or the raw
71
- * identifier when the check was skipped for a policy-wide caller.
72
- */
73
- var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
74
- fetchIdentifier;
75
- isResolved;
76
- constructor(fetchIdentifier, isResolved) {
77
- this.fetchIdentifier = fetchIdentifier;
78
- this.isResolved = isResolved;
79
- }
80
- static resolved(documentId) {
81
- return new AuthorizedDocumentHandle(documentId, true);
82
- }
83
- static skipped(identifier) {
84
- return new AuthorizedDocumentHandle(identifier, false);
85
- }
86
- /** The verified canonical id; throws when resolution was skipped. */
87
- canonicalId() {
88
- if (!this.isResolved) throw new Error("Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller");
89
- return this.fetchIdentifier;
90
- }
91
- };
92
- const AuthorizationPolicy = {
93
- OPEN: "OPEN",
94
- ADMIN_ONLY: "ADMIN_ONLY",
95
- DOCUMENT_PERMISSIONS: "DOCUMENT_PERMISSIONS"
96
- };
97
- /** Shared config holder and admin-list check for the policy strategies. */
98
- var BaseAuthorizationService = class {
99
- config;
100
- constructor(config) {
101
- this.config = config;
102
- }
103
- isSupremeAdmin(userAddress) {
104
- if (!userAddress) return false;
105
- return this.config.admins.includes(userAddress.toLowerCase());
106
- }
107
- };
108
- /** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */
109
- var OpenAuthorizationService = class extends BaseAuthorizationService {
110
- isSupremeAdmin() {
111
- return true;
112
- }
113
- canCreate() {
114
- return true;
115
- }
116
- canRead() {
117
- return Promise.resolve(true);
118
- }
119
- canWrite() {
120
- return Promise.resolve(true);
121
- }
122
- canManage() {
123
- return Promise.resolve(true);
124
- }
125
- canMutate() {
126
- return Promise.resolve(true);
127
- }
128
- };
129
- /** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */
130
- var AdminOnlyAuthorizationService = class extends BaseAuthorizationService {
131
- canCreate(userAddress) {
132
- return this.isSupremeAdmin(userAddress);
133
- }
134
- canRead(_documentId, userAddress) {
135
- return Promise.resolve(this.isSupremeAdmin(userAddress));
136
- }
137
- canWrite(_documentId, userAddress) {
138
- return Promise.resolve(this.isSupremeAdmin(userAddress));
139
- }
140
- canManage(_documentId, userAddress) {
141
- return Promise.resolve(this.isSupremeAdmin(userAddress));
142
- }
143
- canMutate(_documentId, _operationType, userAddress) {
144
- return Promise.resolve(this.isSupremeAdmin(userAddress));
145
- }
146
- };
147
- const PERMISSION_RANK = {
148
- READ: 1,
149
- WRITE: 2,
150
- ADMIN: 3
151
- };
152
- function satisfies(level, required) {
153
- return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];
154
- }
155
- /**
156
- * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.
157
- *
158
- * All decisions live here; DocumentPermissionService is the data-access
159
- * layer underneath (grants, protection rows, owners).
160
- */
161
- var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationService {
162
- #permissions;
163
- #getParentIds;
164
- constructor(permissions, getParentIds, config) {
165
- super(config);
166
- this.#permissions = permissions;
167
- this.#getParentIds = getParentIds;
168
- }
169
- canCreate(userAddress) {
170
- return this.isSupremeAdmin(userAddress) || !!userAddress;
171
- }
172
- canRead(documentId, userAddress) {
173
- return this.#canAccess(documentId, "READ", userAddress);
174
- }
175
- canWrite(documentId, userAddress) {
176
- return this.#canAccess(documentId, "WRITE", userAddress);
177
- }
178
- canManage(documentId, userAddress) {
179
- return this.#isDocumentAdmin(documentId, userAddress);
180
- }
181
- async canMutate(documentId, operationType, userAddress) {
182
- if (this.isSupremeAdmin(userAddress)) return true;
183
- if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
184
- if (!userAddress) return false;
185
- if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
186
- return this.#permissions.hasOperationGrant(documentId, operationType, userAddress);
187
- }
188
- return this.#canAccess(documentId, "WRITE", userAddress);
189
- }
190
- /**
191
- * The one "administers this document" predicate: supreme admin, document
192
- * owner, or ADMIN grant on the document itself.
193
- */
194
- async #isDocumentAdmin(documentId, userAddress) {
195
- if (this.isSupremeAdmin(userAddress)) return true;
196
- if (!userAddress) return false;
197
- const owner = await this.#permissions.getDocumentOwner(documentId);
198
- if (owner && owner === userAddress.toLowerCase()) return true;
199
- return satisfies(await this.#grantLevel(documentId, userAddress), "ADMIN");
200
- }
201
- /**
202
- * The one read/write decision shape: supreme admin → unprotected (self or
203
- * ancestor) → owner → inherited grant of at least the required level.
204
- */
205
- async #canAccess(documentId, required, userAddress) {
206
- if (this.isSupremeAdmin(userAddress)) return true;
207
- if (!await this.#permissions.isProtectedWithAncestors(documentId, this.#getParentIds)) return true;
208
- if (!userAddress) return false;
209
- const owner = await this.#permissions.getDocumentOwner(documentId);
210
- if (owner && owner === userAddress.toLowerCase()) return true;
211
- return this.#hasGrantInHierarchy(documentId, userAddress, required);
212
- }
213
- /** Best grant the user holds on the document. */
214
- async #grantLevel(documentId, userAddress) {
215
- return this.#permissions.getUserPermission(documentId, userAddress);
216
- }
217
- /**
218
- * Walks the parent hierarchy (with cycle protection) looking for a grant of
219
- * at least the required level on the document or any ancestor.
220
- */
221
- async #hasGrantInHierarchy(documentId, userAddress, required) {
222
- const visited = /* @__PURE__ */ new Set();
223
- const queue = [documentId];
224
- while (queue.length > 0) {
225
- const current = queue.shift();
226
- if (visited.has(current)) continue;
227
- visited.add(current);
228
- if (satisfies(await this.#grantLevel(current, userAddress), required)) return true;
229
- for (const parentId of await this.#getParentIds(current)) if (!visited.has(parentId)) queue.push(parentId);
230
- }
231
- return false;
232
- }
233
- };
234
- /**
235
- * Selects the strategy for the configured policy. The strategy classes are
236
- * not exported, so this guard is the only construction path.
237
- */
238
- function createAuthorizationService(config, documentPermissionService, getParentIds) {
239
- if (config.policy === AuthorizationPolicy.OPEN) return new OpenAuthorizationService(config);
240
- if (config.policy === AuthorizationPolicy.ADMIN_ONLY) return new AdminOnlyAuthorizationService(config);
241
- if (!documentPermissionService) throw new Error("DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy");
242
- if (!getParentIds) throw new Error("A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy");
243
- return new DocumentPermissionsAuthorizationService(documentPermissionService, getParentIds, config);
244
- }
245
- //#endregion
246
- //#region src/services/canonical-document-id.ts
247
- /**
248
- * Raised when a caller-supplied identifier cannot be resolved to a canonical
249
- * document id. Carries no detail on purpose: resolution failures must not act
250
- * as a document-existence oracle, so consumers map this to their generic
251
- * fail-closed response.
252
- */
253
- var CanonicalDocumentIdResolutionError = class extends Error {
254
- constructor() {
255
- super("Document identifier could not be resolved");
256
- this.name = "CanonicalDocumentIdResolutionError";
257
- }
258
- };
259
- /**
260
- * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer
261
- * and server routes must resolve caller identifiers through this helper so
262
- * decision and data layers always agree on the subject document.
263
- */
264
- function createCanonicalDocumentIdResolver(client) {
265
- return async (identifier) => {
266
- let resolved;
267
- try {
268
- resolved = await client.resolveIdOrSlug(identifier);
269
- } catch {
270
- throw new CanonicalDocumentIdResolutionError();
271
- }
272
- return resolved;
273
- };
274
- }
275
- //#endregion
276
- //#region src/graphql/base-subgraph.ts
277
- /**
278
- * The subject a request reads as: its address and the app key its token
279
- * carries. Anonymous is an empty subject, never the host's signer.
280
- */
281
- function callerSubject(user) {
282
- return {
283
- address: user?.address,
284
- key: user?.appKey
285
- };
286
- }
287
- var BaseSubgraph = class {
288
- name = "example";
289
- path = "";
290
- resolvers = { Query: { hello: () => this.name } };
291
- typeDefs = gql`
292
- type Query {
293
- hello: String
294
- }
295
- `;
296
- reactorClient;
297
- /** This package's namespaced slice of the HTTP surface. */
298
- http;
299
- graphqlManager;
300
- relationalDb;
301
- syncManager;
302
- documentPermissionService;
303
- authorizationService;
304
- syncServingGate;
305
- /**
306
- * Per-request memo of raw identifier to canonical document id, keyed on the
307
- * request context object so entries are released when the request ends. Lets
308
- * batch resolvers resolve each distinct identifier at most once.
309
- */
310
- #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
311
- #resolveCanonical;
312
- constructor(args) {
313
- this.#resolveCanonical = createCanonicalDocumentIdResolver(args.reactorClient);
314
- this.http = args.http;
315
- this.reactorClient = args.reactorClient;
316
- this.graphqlManager = args.graphqlManager;
317
- this.relationalDb = args.relationalDb;
318
- this.syncManager = args.syncManager;
319
- this.documentPermissionService = args.documentPermissionService;
320
- this.authorizationService = args.authorizationService;
321
- this.syncServingGate = args.syncServingGate;
322
- this.path = args.path ?? "";
323
- }
324
- async onSetup() {}
325
- async onDisconnect() {}
326
- /**
327
- * Resolves a caller-supplied identifier (id or slug) to its canonical
328
- * document id, memoized per request. Both the decision layer and the data
329
- * layer must agree on the subject, so this runs the same resolveIdOrSlug
330
- * lookup the data path uses. A resolution failure (not found, ambiguous, or
331
- * transient) surfaces as a generic Forbidden, fail-closed, so a bad
332
- * identifier cannot be used as a document-existence oracle.
333
- */
334
- async resolveCanonicalDocumentId(identifier, requestKey) {
335
- let cache = this.#canonicalIdMemo.get(requestKey);
336
- if (!cache) {
337
- cache = /* @__PURE__ */ new Map();
338
- this.#canonicalIdMemo.set(requestKey, cache);
339
- }
340
- const cached = cache.get(identifier);
341
- if (cached !== void 0) return cached;
342
- let canonical;
343
- try {
344
- canonical = await this.#resolveCanonical(identifier);
345
- } catch {
346
- throw new ForbiddenError();
347
- }
348
- cache.set(identifier, canonical);
349
- return canonical;
350
- }
351
- /**
352
- * Resolves the args' `documentId` to canonical form. Unconditional (unlike the
353
- * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.
354
- */
355
- async withCanonicalDocumentId(args, requestKey) {
356
- const documentId = await this.resolveCanonicalDocumentId(args.documentId, requestKey);
357
- return {
358
- ...args,
359
- documentId
360
- };
361
- }
362
- /**
363
- * Resolves an identifier for a per-document check, or null when the caller has
364
- * policy-wide access (OPEN or supreme admin) and the check can be skipped.
365
- * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail
366
- * closed without resolving.
367
- */
368
- async #resolveForCheck(identifier, ctx) {
369
- if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return null;
370
- if (this.authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
371
- return this.resolveCanonicalDocumentId(identifier, ctx);
372
- }
373
- /**
374
- * Read filter for an already-canonical document id (one sourced from the data
375
- * layer, such as a fetched document's id). Performs no slug resolution.
376
- */
377
- async canReadDocument(documentId, ctx) {
378
- return this.authorizationService.canRead(documentId, ctx.user?.address);
379
- }
380
- /**
381
- * The principal a request decides as: the authenticated caller's address, and
382
- * the did:key of the app instance whose token authenticated it.
383
- *
384
- * Both, because a policy can name either. The key is what a document records
385
- * as its creator, so a subject built without one cannot match the creator's
386
- * standing permission over the auth scope -- the document's own creator would
387
- * be refused an operation the write path accepts, since a signed action
388
- * carries the same key. Anonymous callers supply neither.
389
- */
390
- viewSubject(ctx) {
391
- return callerSubject(ctx.user);
392
- }
393
- /** Whether a listing would serve the document to the caller; fails closed. */
394
- async servesDocument(documentId, ctx) {
395
- if (!documentId) return false;
396
- try {
397
- return await this.reactorClient.isServed(documentId, { subject: this.viewSubject(ctx) });
398
- } catch {
399
- return false;
400
- }
401
- }
402
- /**
403
- * Asserts read access, resolving a slug first. Returns a handle whose
404
- * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.
405
- */
406
- async assertCanRead(identifier, ctx) {
407
- const documentId = await this.#resolveForCheck(identifier, ctx);
408
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
409
- await this.assertCanReadCanonical(documentId, ctx);
410
- return AuthorizedDocumentHandle.resolved(documentId);
411
- }
412
- async assertCanWrite(identifier, ctx) {
413
- const documentId = await this.#resolveForCheck(identifier, ctx);
414
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
415
- await this.assertCanWriteCanonical(documentId, ctx);
416
- return AuthorizedDocumentHandle.resolved(documentId);
417
- }
418
- async assertCanExecuteOperation(identifier, operationType, ctx) {
419
- const documentId = await this.#resolveForCheck(identifier, ctx);
420
- if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
421
- await this.assertCanExecuteOperationCanonical(documentId, operationType, ctx);
422
- return AuthorizedDocumentHandle.resolved(documentId);
423
- }
424
- /**
425
- * Read assertion for an already-canonical document id. No slug resolution;
426
- * use only with ids sourced from the data layer or already resolved.
427
- */
428
- async assertCanReadCanonical(documentId, ctx) {
429
- if (!await this.authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
430
- }
431
- async assertCanWriteCanonical(documentId, ctx) {
432
- if (!await this.authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write to this document");
433
- }
434
- async assertCanExecuteOperationCanonical(documentId, operationType, ctx) {
435
- if (!await this.authorizationService.canMutate(documentId, operationType, ctx.user?.address)) throw new ForbiddenError(`to execute operation "${operationType}" on this document`);
436
- }
437
- assertCanCreate(ctx) {
438
- if (this.authorizationService.canCreate(ctx.user?.address)) return;
439
- if (ctx.user?.address) throw new ForbiddenError("to create documents");
440
- throw new AuthenticationRequiredError("to create documents");
441
- }
442
- };
443
- //#endregion
444
- //#region src/packages/import-resolver.ts
445
- /**
446
- * Imports a specifier that may be either a bare package specifier or a
447
- * filesystem path. Absolute paths are converted to file:// URLs, because the
448
- * ESM loader reads the drive letter in a Windows path as a URL scheme
449
- * (`import('D:\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).
450
- */
451
- async function importSpecifier(target) {
452
- return await (path.isAbsolute(target) ? import(pathToFileURL(target).href) : import(target));
453
- }
454
- /**
455
- * Attempts to import from suggested Node.js paths
456
- */
457
- async function tryNodeSuggestedPaths(packageName, subPath) {
458
- const suggestedPaths = [
459
- `${packageName}/dist/node/${subPath}/index.mjs`,
460
- `${packageName}/dist/node/${subPath}.mjs`,
461
- `${packageName}/dist/${subPath}/index.js`,
462
- `${packageName}/dist/${subPath}.js`
463
- ];
464
- for (const suggestedPath of suggestedPaths) try {
465
- return await importSpecifier(suggestedPath);
466
- } catch {}
467
- return null;
468
- }
469
- /**
470
- * Attempts to resolve package using import.meta.resolve
471
- */
472
- async function tryImportMetaResolve(packageName, subPath) {
473
- try {
474
- const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
475
- if (!resolvedUrl) return null;
476
- const packageRoot = path.dirname(fileURLToPath(resolvedUrl));
477
- const pathsToTry = [
478
- path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
479
- path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
480
- path.join(packageRoot, "dist", subPath, "index.js"),
481
- path.join(packageRoot, "dist", `${subPath}.js`),
482
- path.join(packageRoot, subPath, "index.js"),
483
- path.join(packageRoot, `${subPath}.js`)
484
- ];
485
- for (const attemptPath of pathsToTry) try {
486
- return await importSpecifier(attemptPath);
487
- } catch {}
488
- } catch {}
489
- return null;
490
- }
491
- /**
492
- * Resolves symlinks in node_modules to find the real package location
493
- */
494
- async function resolveSymlinkedPaths(packageName, subPath) {
495
- const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
496
- const nodeModulesPatterns = [path.join(process.cwd(), "node_modules", packageName), path.join(process.cwd(), "node_modules", packageBaseName || packageName)];
497
- const workspacePatterns = [];
498
- for (const nodeModulesPath of nodeModulesPatterns) try {
499
- const fs = await import("node:fs");
500
- if (fs.existsSync(nodeModulesPath)) {
501
- const realPath = fs.realpathSync(nodeModulesPath);
502
- workspacePatterns.push(path.join(realPath, "dist", "node", subPath, "index.mjs"), path.join(realPath, "dist", "node", `${subPath}.mjs`), path.join(realPath, "dist", subPath, "index.js"), path.join(realPath, "dist", `${subPath}.js`), path.join(realPath, subPath, "index.js"), path.join(realPath, `${subPath}.js`));
503
- }
504
- } catch {}
505
- return workspacePatterns;
506
- }
507
- /**
508
- * Generates common workspace pattern paths
509
- */
510
- function getCommonWorkspacePaths(packageName, subPath) {
511
- const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
512
- const commonRoots = [process.cwd(), path.dirname(process.cwd())];
513
- const workspacePatterns = [];
514
- for (const root of commonRoots) workspacePatterns.push(path.join(root, "packages", packageBaseName || packageName, "dist", "node", subPath, "index.mjs"), path.join(root, "packages", packageBaseName || packageName, "dist", "node", `${subPath}.mjs`), path.join(root, "packages", packageBaseName || packageName, "dist", subPath, "index.js"), path.join(root, "packages", packageBaseName || packageName, "dist", `${subPath}.js`));
515
- return workspacePatterns;
516
- }
517
- /**
518
- * Attempts to import from a list of workspace patterns
519
- */
520
- async function tryWorkspacePatterns(patterns) {
521
- for (const workspacePath of patterns) try {
522
- return await importSpecifier(workspacePath);
523
- } catch {}
524
- return null;
525
- }
526
- /**
527
- * Attempts to resolve linked packages using various fallback strategies
528
- */
529
- async function resolveLinkedPackage(packageName, subPath) {
530
- let result = await tryNodeSuggestedPaths(packageName, subPath);
531
- if (result) return result;
532
- result = await tryImportMetaResolve(packageName, subPath);
533
- if (result) return result;
534
- result = await tryWorkspacePatterns(await resolveSymlinkedPaths(packageName, subPath));
535
- if (result) return result;
536
- result = await tryWorkspacePatterns(getCommonWorkspacePaths(packageName, subPath));
537
- if (result) return result;
538
- return null;
539
- }
540
- //#endregion
541
- //#region src/packages/util.ts
542
- childLogger(["reactor-api", "packages/util"]);
543
- /**
544
- * Tries to import document models from a package. This function cannot throw.
545
- */
546
- async function loadDocumentModels(packageName) {
547
- return loadDependency(packageName, "document-models");
548
- }
549
- /**
550
- * Tries to import subgraphs from a package. This function cannot throw.
551
- */
552
- async function loadSubgraphs(packageName) {
553
- return loadDependency(packageName, "subgraphs");
554
- }
555
- /**
556
- * Tries to import processors from a package. This function cannot throw.
557
- */
558
- async function loadProcessors(packageName) {
559
- return loadDependency(packageName, "processors");
560
- }
561
- /**
562
- * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.
563
- * Returns null if the dependency cannot be loaded.
564
- */
565
- async function loadDependency(packageName, subPath) {
566
- const fullPath = path.isAbsolute(packageName) ? pathToFileURL(path.join(packageName, subPath)).href : `${packageName}/${subPath}`;
567
- try {
568
- return await import(
569
- /* @vite-ignore */
570
- fullPath
571
- );
572
- } catch (e) {
573
- if (e instanceof Error && "code" in e && (e.code === "ERR_MODULE_NOT_FOUND" || e.code === "ERR_UNSUPPORTED_DIR_IMPORT" || e.code === "ERR_UNSUPPORTED_ESM_URL_SCHEME")) {
574
- const result = await resolveLinkedPackage(packageName, subPath);
575
- if (result) return result;
576
- }
577
- throw e;
578
- }
579
- }
580
- function isUpgradeManifest(value) {
581
- return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
582
- }
583
- /**
584
- * Collects upgrade manifests from a package's document-models namespace.
585
- * Handles both the aggregate `upgradeManifests` array export and individual
586
- * manifest exports; dedupes by documentType.
587
- */
588
- function extractUpgradeManifests(namespace) {
589
- const manifests = /* @__PURE__ */ new Map();
590
- const add = (value) => {
591
- if (isUpgradeManifest(value)) manifests.set(value.documentType, value);
592
- };
593
- for (const value of Object.values(namespace)) if (Array.isArray(value)) value.forEach(add);
594
- else add(value);
595
- return Array.from(manifests.values());
596
- }
597
- function debounce(func, delay = 250) {
598
- let timer;
599
- return (immediate = false, ...args) => {
600
- if (timer) clearTimeout(timer);
601
- return new Promise((resolve, reject) => {
602
- if (immediate) func(...args).then(resolve).catch(reject);
603
- else timer = setTimeout(() => {
604
- func(...args).then(resolve).catch(reject);
605
- }, delay);
606
- });
607
- };
608
- }
609
- function isSubpath(parent, dir) {
610
- const relative = path.relative(parent, dir);
611
- return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
612
- }
613
- //#endregion
614
- //#region src/graphql/utils.ts
615
- function isSubgraphClass(candidate) {
616
- if (typeof candidate !== "function") return false;
617
- let proto = Object.getPrototypeOf(candidate);
618
- while (proto) {
619
- if (Object.prototype.isPrototypeOf.call(proto, BaseSubgraph)) return true;
620
- proto = Object.getPrototypeOf(proto);
621
- }
622
- return false;
623
- }
624
- function buildGraphqlOperations(operations, skip, first) {
625
- return operations.slice(skip, skip + first).map(buildGraphqlOperation);
626
- }
627
- function buildGraphqlOperation(operation) {
628
- const signer = operation.action.context?.signer;
629
- return {
630
- id: operation.id ?? "",
631
- type: operation.action.type,
632
- index: operation.index,
633
- timestampUtcMs: operation.timestampUtcMs,
634
- hash: operation.hash,
635
- skip: operation.skip,
636
- inputText: typeof operation.action.input === "string" ? operation.action.input : JSON.stringify(operation.action.input),
637
- error: operation.error,
638
- context: { signer: signer ? {
639
- user: signer.user,
640
- app: signer.app,
641
- signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
642
- } : void 0 }
643
- };
644
- }
645
- function buildGraphQlDocument(doc) {
646
- const state = doc.state;
647
- const initialState = doc.initialState;
648
- const globalState = "global" in doc.state ? doc.state.global : {};
649
- return {
650
- id: doc.header.id,
651
- name: doc.header.name,
652
- documentType: doc.header.documentType,
653
- revision: doc.header.revision.global || 0,
654
- createdAtUtcIso: doc.header.createdAtUtcIso,
655
- lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,
656
- operations: [],
657
- stateJSON: globalState,
658
- state,
659
- initialState
660
- };
661
- }
662
- function buildGraphQlDriveDocument(doc) {
663
- return {
664
- ...buildGraphQlDocument(doc),
665
- meta: { preferredEditor: doc.header.meta?.preferredEditor },
666
- slug: doc.header.slug,
667
- state: doc.state.global,
668
- initialState: doc.state.global
669
- };
670
- }
671
- //#endregion
672
- //#region src/packages/pieces.ts
673
- /** The sub-entry every loader asks a package for its pieces through. */
674
- const PIECES_SUBPATH = "pieces";
675
- const BUILT_PIECE_LIST = packageJsonExports["./pieces"].node;
676
- /** Where a package keeps its piece sources, for telling unbuilt from absent. */
677
- const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, "index.ts");
678
- /** The nearest enclosing package.json, which `exports` usually hides. */
679
- function packageRootOf(dir) {
680
- let current = dir;
681
- while (!existsSync(join(current, "package.json"))) {
682
- const parent = dirname(current);
683
- if (parent === current) return void 0;
684
- current = parent;
685
- }
686
- return current;
687
- }
688
- function resolvePieceList(specifier, hostDir) {
689
- try {
690
- return fileURLToPath(import.meta.resolve(specifier));
691
- } catch (error) {
692
- try {
693
- return createRequire(join(hostDir, "package.json")).resolve(specifier);
694
- } catch {
695
- throw error;
696
- }
697
- }
698
- }
699
- function pieceListLocation(identifier, hostDir = process.cwd()) {
700
- if (isAbsolute(identifier)) return {
701
- root: identifier,
702
- listPath: join(identifier, BUILT_PIECE_LIST)
703
- };
704
- const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);
705
- const root = packageRootOf(dirname(listPath));
706
- if (!root) throw new Error(`No package.json above ${listPath}`);
707
- return {
708
- root,
709
- listPath
710
- };
711
- }
712
- function packageVersionAt(root) {
713
- try {
714
- const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
715
- return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : void 0;
716
- } catch {
717
- return;
718
- }
719
- }
720
- function locatePieces(declared, context) {
721
- const { root, identifier, logger, version } = context;
722
- const located = [];
723
- for (const piece of declared) {
724
- const where = piece.entry ?? piece.bundle;
725
- if (typeof where !== "string" || where === "") {
726
- logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
727
- continue;
728
- }
729
- const path = isAbsolute(where) ? where : join(root, where);
730
- if (!(piece.entry ? existsSync(path) : existsSync(join(path, "package.json")))) {
731
- logger.warn("Piece @piece of @pkg is declared but not built at @path", piece.name, identifier, path);
732
- continue;
733
- }
734
- located.push({
735
- name: piece.name,
736
- version,
737
- ...piece.entry ? { entryPath: path } : { bundleDir: path }
738
- });
739
- }
740
- return located;
741
- }
742
- function declaredPieces(module, identifier, logger) {
743
- const namespace = module ?? {};
744
- const declared = namespace.pieces ?? namespace.default;
745
- if (!Array.isArray(declared)) {
746
- logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", identifier);
747
- return;
748
- }
749
- return declared;
750
- }
751
- function piecesFromCdnList(module, baseUrl, identifier, logger, version) {
752
- const declared = declaredPieces(module, identifier, logger);
753
- if (!declared) return [];
754
- const located = [];
755
- for (const piece of declared) {
756
- const where = piece.entry ?? piece.bundle;
757
- if (typeof where !== "string" || where === "") {
758
- logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
759
- continue;
760
- }
761
- located.push({
762
- name: piece.name,
763
- version,
764
- entryUrl: `${baseUrl}${where.replace(/^dist\/node\/pieces\//, "")}`
765
- });
766
- }
767
- return located;
768
- }
769
- function piecesFromListModule(module, context) {
770
- const namespace = module ?? {};
771
- const declared = namespace.pieces ?? namespace.default;
772
- if (!Array.isArray(declared)) {
773
- context.logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", context.identifier);
774
- return [];
775
- }
776
- const version = packageVersionAt(context.root);
777
- if (!version) {
778
- context.logger.warn("@pkg has no version in @root/package.json, and a piece takes its package's version; its pieces contribute none", context.identifier, context.root);
779
- return [];
780
- }
781
- return locatePieces(declared, {
782
- ...context,
783
- version
784
- });
785
- }
786
- //#endregion
787
- export { AuthorizationPolicy as C, AuthenticationRequiredError as D, AuthEvaluationUnsupportedError as E, ForbiddenError as O, createCanonicalDocumentIdResolver as S, createAuthorizationService as T, loadProcessors as _, pieceListLocation as a, callerSubject as b, buildGraphQlDocument as c, buildGraphqlOperations as d, isSubgraphClass as f, loadDocumentModels as g, isSubpath as h, packageRootOf as i, MalformedStoredOperationError as k, buildGraphQlDriveDocument as l, extractUpgradeManifests as m, PIECES_SUBPATH as n, piecesFromCdnList as o, debounce as p, PIECE_SOURCE_LIST as r, piecesFromListModule as s, BUILT_PIECE_LIST as t, buildGraphqlOperation as u, loadSubgraphs as v, AuthorizedDocumentHandle as w, CanonicalDocumentIdResolutionError as x, BaseSubgraph as y };
788
-
789
- //# sourceMappingURL=pieces-swupjgIO.mjs.map
790
- //# debugId=0b933e15-7a73-537c-acf4-89127d6433f5