@powerhousedao/reactor-api 6.2.3-dev.13 → 6.2.3-dev.14

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/dist/index.mjs CHANGED
@@ -1,19 +1,20 @@
1
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]="38c1f129-3370-5df3-8167-295202794a27")}catch(e){}}();
3
- import { _ as createAuthorizationService, a as isSubgraphClass, b as ForbiddenError, d as loadSubgraphs, f as BaseSubgraph, g as AuthorizedDocumentHandle, h as AuthorizationPolicy, i as buildGraphqlOperations, l as loadDocumentModels, m as createCanonicalDocumentIdResolver, n as buildGraphQlDriveDocument, o as debounce, p as CanonicalDocumentIdResolutionError, r as buildGraphqlOperation, s as extractUpgradeManifests, t as buildGraphQlDocument, u as loadProcessors, v as AuthEvaluationUnsupportedError, x as MalformedStoredOperationError, y as AuthenticationRequiredError } from "./utils-Cm6WbGyq.mjs";
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]="85127713-3ea7-598b-ab85-9f2a928574fb")}catch(e){}}();
3
+ import { C as AuthEvaluationUnsupportedError, E as MalformedStoredOperationError, S as createAuthorizationService, T as ForbiddenError, _ as BaseSubgraph, a as piecesFromListModule, b as AuthorizationPolicy, c as buildGraphqlOperation, d as debounce, f as extractUpgradeManifests, g as loadSubgraphs, h as loadProcessors, i as pieceListLocation, l as buildGraphqlOperations, m as loadDocumentModels, o as buildGraphQlDocument, r as PIECE_SOURCE_LIST, s as buildGraphQlDriveDocument, u as isSubgraphClass, v as CanonicalDocumentIdResolutionError, w as AuthenticationRequiredError, x as AuthorizedDocumentHandle, y as createCanonicalDocumentIdResolver } from "./pieces-DKOEzTAY.mjs";
4
4
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
5
5
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { gql } from "graphql-tag";
7
7
  import { GraphQLError, Kind, parse, print } from "graphql";
8
8
  import { AuthEnforcementDisabledError, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, ModelReadGate, PropagationMode as PropagationMode$1, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl, readDecisionModel, syncOperationErrorType } from "@powerhousedao/reactor";
9
9
  import { ConsoleLogger, childLogger, documentModelDocumentModelModule } from "document-model";
10
- import path, { join } from "node:path";
10
+ import path, { isAbsolute, join } from "node:path";
11
11
  import { match } from "path-to-regexp";
12
12
  import posix from "node:path/posix";
13
13
  import { Readable } from "node:stream";
14
- import fs, { readFileSync, watchFile } from "node:fs";
14
+ import fs, { existsSync, readFileSync, watchFile } from "node:fs";
15
15
  import { pipeline } from "node:stream/promises";
16
16
  import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
17
+ import { pathToFileURL } from "node:url";
17
18
  import { buildSubgraphSchema } from "@apollo/subgraph";
18
19
  import { typeDefs } from "@powerhousedao/document-engineering/graphql";
19
20
  import { camelCase, kebabCase, pascalCase } from "change-case";
@@ -6368,10 +6369,10 @@ const ADMIN_USERS = getAdminUsers();
6368
6369
  //#endregion
6369
6370
  //#region src/graphql/system/version.ts
6370
6371
  function getVersion() {
6371
- return "6.2.3-dev.13";
6372
+ return "6.2.3-dev.14";
6372
6373
  }
6373
6374
  function getGitHash() {
6374
- return "d0567f6f11ec778d8a0a6afb48f32e22eb34ccaa";
6375
+ return "406211da8687ab3d918f6020d754e03ddd50c103";
6375
6376
  }
6376
6377
  function getGitUrl() {
6377
6378
  return buildTreeUrl(getGitHash());
@@ -6425,6 +6426,8 @@ var HttpPackageLoader = class {
6425
6426
  registryUrl;
6426
6427
  logger = childLogger(["reactor-api", "http-loader"]);
6427
6428
  name = "HttpPackageLoader";
6429
+ /** Said once: the reason is the loader's, not any one package's. */
6430
+ reportedNoPieces = false;
6428
6431
  documentModelLoader;
6429
6432
  constructor(options) {
6430
6433
  this.registryUrl = options.registryUrl.endsWith("/") ? options.registryUrl : `${options.registryUrl}/`;
@@ -6498,6 +6501,13 @@ var HttpPackageLoader = class {
6498
6501
  this.logger.verbose(`No processor factory found in ${packageName}`);
6499
6502
  return null;
6500
6503
  }
6504
+ loadPieces(packageSpec) {
6505
+ if (!this.reportedNoPieces) {
6506
+ this.reportedNoPieces = true;
6507
+ this.logger.info("Pieces are not served over HTTP, so @pkg and every other package loaded from the registry contributes none", packageSpec);
6508
+ }
6509
+ return Promise.resolve([]);
6510
+ }
6501
6511
  /**
6502
6512
  * Load document models from multiple packages.
6503
6513
  * Continues loading even if some packages fail.
@@ -6597,6 +6607,7 @@ var HttpDocumentModelLoader = class {
6597
6607
  var ImportPackageLoader = class {
6598
6608
  logger = childLogger(["reactor-api", "import-loader"]);
6599
6609
  name = "ImportPackageLoader";
6610
+ reportedUnbuilt = /* @__PURE__ */ new Set();
6600
6611
  async loadDocumentModels(identifier) {
6601
6612
  this.logger.verbose(`Loading document models from package: ${identifier}`);
6602
6613
  const pkgModule = await loadDocumentModels(identifier);
@@ -6639,6 +6650,30 @@ var ImportPackageLoader = class {
6639
6650
  this.logger.verbose(` ➜ No Processor Factory found: ${identifier}`);
6640
6651
  return null;
6641
6652
  }
6653
+ async loadPieces(identifier) {
6654
+ this.logger.verbose(`Loading pieces from package: ${identifier}`);
6655
+ const { root, listPath } = pieceListLocation(identifier);
6656
+ if (!existsSync(listPath)) {
6657
+ this.reportUnbuilt(identifier, root, listPath);
6658
+ return [];
6659
+ }
6660
+ const pieces = piecesFromListModule(await import(
6661
+ /* @vite-ignore */
6662
+ pathToFileURL(listPath).href
6663
+ ), {
6664
+ root,
6665
+ identifier,
6666
+ logger: this.logger
6667
+ });
6668
+ this.logger.verbose(` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`);
6669
+ return pieces;
6670
+ }
6671
+ reportUnbuilt(identifier, root, listPath) {
6672
+ if (!isAbsolute(identifier) || this.reportedUnbuilt.has(identifier)) return;
6673
+ if (!existsSync(join(root, PIECE_SOURCE_LIST))) return;
6674
+ this.reportedUnbuilt.add(identifier);
6675
+ this.logger.warn("@pkg declares pieces but @list was never built; run `ph build`", identifier, listPath);
6676
+ }
6642
6677
  };
6643
6678
  //#endregion
6644
6679
  //#region src/packages/package-manager.ts
@@ -6654,10 +6689,12 @@ var ImportPackageLoader = class {
6654
6689
  * either bare (`'pkg'`) or as a subpath (`'pkg/subgraphs'`), since loaders
6655
6690
  * import sub-entries like `${pkg}/subgraphs` / `${pkg}/document-models`.
6656
6691
  */
6657
- function isExpectedLoaderMiss(error, pkg) {
6692
+ function isExpectedLoaderMiss(error, pkg, subPath) {
6658
6693
  if (!(error instanceof Error)) return false;
6659
6694
  const code = error.code;
6660
6695
  if (code === "ERR_UNSUPPORTED_DIR_IMPORT") return true;
6696
+ if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" && subPath !== void 0 && error.message.includes(`'./${subPath}'`)) return true;
6697
+ if (subPath !== void 0 && new RegExp(`^Failed to fetch \\S*/${subPath}/index\\.mjs: 404$`).test(error.message)) return true;
6661
6698
  if (error.message.startsWith("Invalid package name:")) return true;
6662
6699
  if (code === "ERR_MODULE_NOT_FOUND") return error.message.includes(`'${pkg}'`) || error.message.includes(`"${pkg}"`) || error.message.includes(`'${pkg}/`) || error.message.includes(`"${pkg}/`);
6663
6700
  return false;
@@ -6679,6 +6716,7 @@ var PackageManager = class {
6679
6716
  upgradeManifestsMap = /* @__PURE__ */ new Map();
6680
6717
  subgraphsMap = /* @__PURE__ */ new Map();
6681
6718
  processorMap = /* @__PURE__ */ new Map();
6719
+ piecesMap = /* @__PURE__ */ new Map();
6682
6720
  configWatcher;
6683
6721
  debouncedUpdateCallbacks = /* @__PURE__ */ new Map();
6684
6722
  eventEmitter = new EventEmitter();
@@ -6697,10 +6735,12 @@ var PackageManager = class {
6697
6735
  const upgradeManifestsMap = await this.loadUpgradeManifests(packages);
6698
6736
  const subgraphsMap = await this.loadSubgraphs(packages);
6699
6737
  const processorsMap = await this.loadProcessors(packages);
6738
+ const piecesMap = await this.loadPieces(packages);
6700
6739
  this.upgradeManifestsMap = upgradeManifestsMap;
6701
6740
  this.updatePackagesMap(documentModelsMap);
6702
6741
  this.updateSubgraphsMap(subgraphsMap);
6703
6742
  this.updateProcessorsMap(processorsMap);
6743
+ this.updatePiecesMap(piecesMap);
6704
6744
  try {
6705
6745
  this.subscribePackages(packages);
6706
6746
  } catch (error) {
@@ -6710,7 +6750,8 @@ var PackageManager = class {
6710
6750
  documentModels: getUniqueDocumentModels(...Array.from(documentModelsMap.values())),
6711
6751
  upgradeManifests: this.getUniqueUpgradeManifests(),
6712
6752
  subgraphs: subgraphsMap,
6713
- processors: processorsMap
6753
+ processors: processorsMap,
6754
+ pieces: piecesMap
6714
6755
  };
6715
6756
  }
6716
6757
  async loadDocumentModels(packages) {
@@ -6810,9 +6851,34 @@ var PackageManager = class {
6810
6851
  }
6811
6852
  return processorsMap;
6812
6853
  }
6854
+ async loadPieces(packages) {
6855
+ this.logger.debug(`Loading pieces from packages: ${packages.join(", ")}`);
6856
+ const piecesMap = /* @__PURE__ */ new Map();
6857
+ for (const pkg of packages) {
6858
+ const allPieces = [];
6859
+ const failures = [];
6860
+ let succeeded = false;
6861
+ for (const loader of this.loaders) try {
6862
+ allPieces.push(...await loader.loadPieces(pkg));
6863
+ succeeded = true;
6864
+ break;
6865
+ } catch (error) {
6866
+ failures.push({
6867
+ loader: loader.name,
6868
+ error
6869
+ });
6870
+ this.logger.debug(`[${loader.name}] Failed to load pieces from package ${pkg}`, error);
6871
+ }
6872
+ this.maybeWarnAllLoadersFailed("pieces", pkg, succeeded, failures);
6873
+ if (allPieces.length > 0) this.logger.info("Loaded @count piece(s) from package @pkg: @pieces", allPieces.length, pkg, allPieces.map((piece) => piece.name).join(", "));
6874
+ piecesMap.set(pkg, allPieces);
6875
+ }
6876
+ return piecesMap;
6877
+ }
6813
6878
  maybeWarnAllLoadersFailed(kind, pkg, succeeded, failures) {
6814
6879
  if (succeeded || failures.length === 0) return;
6815
- const realFailures = failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg));
6880
+ const subPath = kind === "document models" ? "document-models" : kind;
6881
+ const realFailures = failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg, subPath));
6816
6882
  if (realFailures.length === 0) return;
6817
6883
  const details = realFailures.map(({ loader, error }) => {
6818
6884
  return ` [${loader}] ${error instanceof Error ? error.message : String(error)}`;
@@ -6852,6 +6918,15 @@ var PackageManager = class {
6852
6918
  else processorsMap.set(pkg, pkgProcessors);
6853
6919
  this.updateProcessorsMap(processorsMap);
6854
6920
  }
6921
+ async updatePiecesForPackage(pkg) {
6922
+ this.logger.debug(`Updating pieces for package: ${pkg}`);
6923
+ const pieces = await this.loadPieces([pkg]);
6924
+ const piecesMap = new Map(this.piecesMap);
6925
+ const pkgPieces = pieces.get(pkg) ?? [];
6926
+ if (pkgPieces.length === 0) piecesMap.delete(pkg);
6927
+ else piecesMap.set(pkg, pkgPieces);
6928
+ this.updatePiecesMap(piecesMap);
6929
+ }
6855
6930
  /** Debounced per key so repeated subscribePackages calls reuse one timer. */
6856
6931
  getDebouncedUpdateCallback(key, update) {
6857
6932
  if (!this.debouncedUpdateCallbacks.has(key)) {
@@ -6870,10 +6945,12 @@ var PackageManager = class {
6870
6945
  const onDocumentModels = this.getDebouncedUpdateCallback(`${pkg}:document-models`, () => this.updateDocumentModelsForPackage(pkg));
6871
6946
  const onSubgraphs = this.getDebouncedUpdateCallback(`${pkg}:subgraphs`, () => this.updateSubgraphsForPackage(pkg));
6872
6947
  const onProcessors = this.getDebouncedUpdateCallback(`${pkg}:processors`, () => this.updateProcessorsForPackage(pkg));
6948
+ const onPieces = this.getDebouncedUpdateCallback(`${pkg}:pieces`, () => this.updatePiecesForPackage(pkg));
6873
6949
  for (const loader of this.loaders) {
6874
6950
  if (loader.onDocumentModelsChange) unsubs.push(loader.onDocumentModelsChange(pkg, onDocumentModels));
6875
6951
  if (loader.onSubgraphsChange) unsubs.push(loader.onSubgraphsChange(pkg, onSubgraphs));
6876
6952
  if (loader.onProcessorsChange) unsubs.push(loader.onProcessorsChange(pkg, onProcessors));
6953
+ if (loader.onPiecesChange) unsubs.push(loader.onPiecesChange(pkg, onPieces));
6877
6954
  }
6878
6955
  }
6879
6956
  return () => {
@@ -6921,6 +6998,19 @@ var PackageManager = class {
6921
6998
  this.processorMap = processorsMap;
6922
6999
  this.eventEmitter.emit("processorsChange", processorsMap);
6923
7000
  }
7001
+ updatePiecesMap(piecesMap) {
7002
+ const oldPackages = Array.from(this.piecesMap.keys());
7003
+ const newPackages = Array.from(piecesMap.keys());
7004
+ oldPackages.filter((pkg) => !newPackages.includes(pkg)).forEach((pkg) => {
7005
+ this.logger.info("Removed pieces from: @pkg", pkg);
7006
+ });
7007
+ this.piecesMap = piecesMap;
7008
+ this.eventEmitter.emit("piecesChange", piecesMap);
7009
+ }
7010
+ /** The pieces every loaded package ships, keyed by the package. */
7011
+ getPieces() {
7012
+ return new Map(this.piecesMap);
7013
+ }
6924
7014
  /**
6925
7015
  * Remove `pkg` from all package maps and emit the change events, tearing
6926
7016
  * down everything the package registered (subgraphs, processors, document
@@ -6939,9 +7029,11 @@ var PackageManager = class {
6939
7029
  this.upgradeManifestsMap = dropKey(this.upgradeManifestsMap);
6940
7030
  this.subgraphsMap = dropKey(this.subgraphsMap);
6941
7031
  this.processorMap = dropKey(this.processorMap);
7032
+ this.piecesMap = dropKey(this.piecesMap);
6942
7033
  this.updatePackagesMap(this.docModelsMap);
6943
7034
  this.updateSubgraphsMap(this.subgraphsMap);
6944
7035
  this.updateProcessorsMap(this.processorMap);
7036
+ this.updatePiecesMap(this.piecesMap);
6945
7037
  }
6946
7038
  onDocumentModelsChange(handler) {
6947
7039
  this.eventEmitter.on("documentModelsChange", handler);
@@ -6952,6 +7044,9 @@ var PackageManager = class {
6952
7044
  onProcessorsChange(handler) {
6953
7045
  this.eventEmitter.on("processorsChange", handler);
6954
7046
  }
7047
+ onPiecesChange(handler) {
7048
+ this.eventEmitter.on("piecesChange", handler);
7049
+ }
6955
7050
  };
6956
7051
  //#endregion
6957
7052
  //#region src/config.ts
@@ -8583,4 +8678,4 @@ var PackageManagementService = class {
8583
8678
  export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessService, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, FindDocumentsDocument, ForbiddenError, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InvalidNamespaceError, JobChangesDocument, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WebhookService, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createMergedSchema, createReactorGraphQLClient, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, driveIdFromUrl, extractSubgraphsFromModule, generateDocumentModelSchema, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelTypeDefs, getExplorerPrefix, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, initAnalyticsStoreSql, initializeAndStartAPI, isDefinedNonNullAny, isExpectedLoaderMiss, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, redactHeaders, renderGraphqlPlayground, resolvePackageName, resolveRenownConfig, verifyWebhook };
8584
8679
 
8585
8680
  //# sourceMappingURL=index.mjs.map
8586
- //# debugId=38c1f129-3370-5df3-8167-295202794a27
8681
+ //# debugId=85127713-3ea7-598b-ab85-9f2a928574fb