@powerhousedao/reactor-api 6.2.3-dev.78 → 6.2.3-dev.79

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 (25) hide show
  1. package/dist/{base-document-models-By4P20-z.mjs → base-document-models-ux7TZ9X3.mjs} +5 -5
  2. package/dist/{base-document-models-By4P20-z.mjs.map → base-document-models-ux7TZ9X3.mjs.map} +1 -1
  3. package/dist/index.d.mts +843 -780
  4. package/dist/index.d.mts.map +1 -1
  5. package/dist/index.mjs +417 -359
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{package-subgraph-check-6tK9LMg1.mjs → package-subgraph-check-BGfeyfnc.mjs} +4 -4
  8. package/dist/{package-subgraph-check-6tK9LMg1.mjs.map → package-subgraph-check-BGfeyfnc.mjs.map} +1 -1
  9. package/dist/{pglite-node-DOFZDYCK.mjs → pglite-node-DGms6Ssa.mjs} +18 -5
  10. package/dist/pglite-node-DGms6Ssa.mjs.map +1 -0
  11. package/dist/src/graphql/subgraph-types.mjs +1 -1
  12. package/dist/src/packages/vite-loader.d.mts +2 -2
  13. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  14. package/dist/src/packages/vite-loader.mjs +29 -10
  15. package/dist/src/packages/vite-loader.mjs.map +1 -1
  16. package/dist/src/pglite/pglite-node.d.mts +5 -0
  17. package/dist/src/pglite/pglite-node.d.mts.map +1 -1
  18. package/dist/src/pglite/pglite-node.mjs +4 -4
  19. package/dist/{subgraph-extraction-zUDn2zX_.mjs → subgraph-extraction-BYKOycxo.mjs} +18 -4
  20. package/dist/subgraph-extraction-BYKOycxo.mjs.map +1 -0
  21. package/dist/{types-CCI5IDgT.d.mts → types-BEpxtyKW.d.mts} +2 -2
  22. package/dist/{types-CCI5IDgT.d.mts.map → types-BEpxtyKW.d.mts.map} +1 -1
  23. package/package.json +13 -13
  24. package/dist/pglite-node-DOFZDYCK.mjs.map +0 -1
  25. package/dist/subgraph-extraction-zUDn2zX_.mjs.map +0 -1
@@ -1,6 +1,6 @@
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]="31ad7f34-589c-56f4-b573-e8a5acd1a88a")}catch(e){}}();
3
- import { A as getDocumentModelSubgraphName, E as findSubgraphTypeCollisions, L as schema_default$1, M as getGeneratedDocumentModelTypes, O as generatedTypesOf, P as reservedTypeNames, a as inspectionAdminTypeDefs, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache } from "./base-document-models-By4P20-z.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]="e70c1355-2855-5f25-92d3-9c6792ff9058")}catch(e){}}();
3
+ import { A as getDocumentModelSubgraphName, E as findSubgraphTypeCollisions, L as schema_default$1, M as getGeneratedDocumentModelTypes, O as generatedTypesOf, P as reservedTypeNames, a as inspectionAdminTypeDefs, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache } from "./base-document-models-ux7TZ9X3.mjs";
4
4
  import "./subgraph-schema-owner-BEjuk2Xv.mjs";
5
5
  import { typedefs } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { gql } from "graphql-tag";
@@ -134,5 +134,5 @@ function checkPackageSubgraphs(subgraphs, documentModels) {
134
134
  //#endregion
135
135
  export { checkPackageSubgraphs };
136
136
 
137
- //# sourceMappingURL=package-subgraph-check-6tK9LMg1.mjs.map
138
- //# debugId=31ad7f34-589c-56f4-b573-e8a5acd1a88a
137
+ //# sourceMappingURL=package-subgraph-check-BGfeyfnc.mjs.map
138
+ //# debugId=e70c1355-2855-5f25-92d3-9c6792ff9058
@@ -1 +1 @@
1
- {"version":3,"file":"package-subgraph-check-6tK9LMg1.mjs","sources":["../src/graphql/package-subgraph-check.ts"],"sourcesContent":["import { typedefs as analyticsTypeDefs } from \"@powerhousedao/analytics-engine-graphql\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { baseDocumentModels } from \"../packages/base-document-models.js\";\nimport {\n DocumentModelSchemaCache,\n type DocumentModelSource,\n findSubgraphTypeCollisions,\n generatedTypesOf,\n getDocumentModelSubgraphName,\n getGeneratedDocumentModelTypes,\n reservedTypeNames,\n} from \"../utils/create-schema.js\";\nimport authSchema from \"./auth/schema.graphql\";\nimport { inspectionAdminTypeDefs } from \"./inspection/admin-schema.js\";\nimport { inspectionTypeDefs } from \"./inspection/schema.js\";\nimport reactorSchema from \"./reactor/schema.graphql\";\nimport {\n type Admission,\n admitDocumentModels,\n CORE_ORIGIN,\n decideAdmission,\n describeOrigin,\n DOCUMENT_MODEL_ORIGIN,\n documentModelSubgraphSources,\n RegistrationOrder,\n type SubgraphOrigin,\n supergraphClaimLosers,\n} from \"./subgraph-admission.js\";\nimport {\n collectSubgraphClaims,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\nimport { systemTypeDefs } from \"./system/schema.js\";\nimport { DOCUMENT_MODEL_SCHEMA_OWNER } from \"./subgraph-schema-owner.js\";\nimport type {\n PackageSubgraph,\n PackageSubgraphConflicts,\n PackageSubgraphReport,\n RefusedDocumentModel,\n} from \"./subgraph-types.js\";\n\n/** The type definitions of every core subgraph, by subgraph name. */\nexport const coreSubgraphTypeDefs: ReadonlyMap<string, DocumentNode> = new Map([\n [\"analytics\", gql(analyticsTypeDefs)],\n [\"system\", systemTypeDefs],\n [\"r\", gql(reactorSchema)],\n [\"inspection\", inspectionTypeDefs],\n [\"inspection-admin\", inspectionAdminTypeDefs],\n [\"auth\", gql(authSchema)],\n]);\n\nconst PACKAGE_ORIGIN: SubgraphOrigin = \"package\";\n\ntype Registered = {\n name: string;\n origin: SubgraphOrigin;\n typeDefs: DocumentNode;\n ownTypeNames?: ReadonlySet<string>;\n};\n\ntype Rejection = Extract<Admission<Registered>, { action: \"reject\" }>;\n\nfunction claimsOf(typeDefs: DocumentNode, generated: ReadonlySet<string>) {\n try {\n return collectSubgraphClaims(typeDefs, generated);\n } catch {\n // Malformed typeDefs fail where the schema is built, so claim nothing.\n return new Map() as SubgraphClaims;\n }\n}\n\nfunction describeModelSubgraphRejection(rejection: Rejection): string {\n switch (rejection.reason) {\n case \"core name\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(CORE_ORIGIN)}`;\n case \"rank\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(rejection.holderOrigin)}`;\n case \"collision\":\n return `its subgraph defines generated types: ${rejection.collisions.join(\", \")}`;\n }\n}\n\nfunction packageConflict(\n rejection: Rejection,\n owners: ReadonlyMap<string, string>,\n): PackageSubgraphConflicts {\n switch (rejection.reason) {\n case \"core name\":\n return { nameHeldBy: \"core\", claims: [] };\n case \"rank\":\n return { nameHeldBy: \"document model\", claims: [] };\n case \"collision\":\n return {\n claims: rejection.collisions.map((claim) => ({\n claim,\n owner: owners.get(claim) ?? DOCUMENT_MODEL_SCHEMA_OWNER,\n })),\n };\n }\n}\n\n/** Server admission replayed for one package; hosts and other packages unknown. */\nexport function checkPackageSubgraphs(\n subgraphs: readonly PackageSubgraph[],\n documentModels: readonly DocumentModelGlobalState[],\n): PackageSubgraphReport {\n const packageModels: DocumentModelSource[] = documentModels.map((global) => ({\n documentModel: { global },\n }));\n const { admitted, schemas, refusals } = admitDocumentModels(\n new DocumentModelSchemaCache<DocumentModelSource>().resolve([\n ...baseDocumentModels.map(([, model]) => model),\n ...packageModels,\n ]),\n reservedTypeNames(coreSubgraphTypeDefs.values()),\n );\n const generated = getGeneratedDocumentModelTypes(admitted, schemas);\n const fixed = generatedTypesOf([]).names;\n const generatedOwners = new Map<string, string>();\n for (const model of admitted) {\n const owner = getDocumentModelSubgraphName(model.documentModel.global);\n const { names } = getGeneratedDocumentModelTypes([model], schemas);\n for (const name of names) {\n if (!fixed.has(name)) generatedOwners.set(name, owner);\n }\n }\n\n const holders = new Map<string, Registered>();\n const order = new RegistrationOrder();\n const register = (entry: Registered): Admission<Registered> => {\n const holder = holders.get(entry.name);\n const admission = decideAdmission(\n entry,\n entry.origin,\n holder ? [{ holder, origin: holder.origin }] : [],\n () => {\n try {\n return findSubgraphTypeCollisions(\n generated,\n entry.typeDefs,\n entry.ownTypeNames,\n );\n } catch {\n return [];\n }\n },\n );\n if (admission.action === \"add\") {\n holders.set(entry.name, entry);\n order.record(entry.origin, entry.name);\n }\n return admission;\n };\n\n for (const [name, typeDefs] of coreSubgraphTypeDefs) {\n register({ name, origin: CORE_ORIGIN, typeDefs });\n }\n\n const refusedModels: RefusedDocumentModel[] = refusals\n .filter(({ model }) => packageModels.includes(model))\n .map(({ model, reason, subgraphOnly }) => ({\n name: model.documentModel.global.name,\n reason,\n subgraphOnly,\n }));\n for (const { model, types } of documentModelSubgraphSources(\n admitted,\n schemas,\n )) {\n const admission = register({\n name: getDocumentModelSubgraphName(model.documentModel.global),\n origin: DOCUMENT_MODEL_ORIGIN,\n typeDefs: types.typeDefs,\n ownTypeNames: types.typeNames,\n });\n if (admission.action === \"reject\" && packageModels.includes(model)) {\n refusedModels.push({\n name: model.documentModel.global.name,\n reason: describeModelSubgraphRejection(admission),\n subgraphOnly: true,\n });\n }\n }\n\n const conflicts = new Map<string, PackageSubgraphConflicts>();\n for (const { name, typeDefs } of subgraphs) {\n const admission = register({ name, origin: PACKAGE_ORIGIN, typeDefs });\n if (admission.action === \"reject\") {\n conflicts.set(name, packageConflict(admission, generatedOwners));\n } else if (admission.action === \"add\" && admission.replaces.length > 0) {\n conflicts.set(name, { nameHeldBy: \"package\", claims: [] });\n }\n }\n\n const excluded = supergraphClaimLosers(\n Array.from(holders.values(), (entry) => ({\n member: entry,\n name: entry.name,\n origin: entry.origin,\n claims: claimsOf(entry.typeDefs, generated.names),\n })),\n order,\n );\n for (const [entry, claims] of excluded) {\n if (entry.origin !== PACKAGE_ORIGIN) continue;\n conflicts.set(entry.name, { ...conflicts.get(entry.name), claims });\n }\n return { conflicts, refusedModels };\n}\n"],"names":["analyticsTypeDefs","reactorSchema","authSchema"],"mappings":";;;;;;;;AA4CA,MAAa,uCAA0D,IAAI,IAAI;CAC7E,CAAC,aAAa,IAAIA,QAAiB,CAAC;CACpC,CAAC,UAAU,cAAc;CACzB,CAAC,KAAK,IAAIC,cAAa,CAAC;CACxB,CAAC,cAAc,kBAAkB;CACjC,CAAC,oBAAoB,uBAAuB;CAC5C,CAAC,QAAQ,IAAIC,gBAAU,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiC;AAWvC,SAAS,SAAS,UAAwB,WAAgC;CACxE,IAAI;EACF,OAAO,sBAAsB,UAAU,SAAS;CAClD,QAAQ;EAEN,uBAAO,IAAI,IAAI;CACjB;AACF;AAEA,SAAS,+BAA+B,WAA8B;CACpE,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO,iDAAiD,eAAe,WAAW;EACpF,KAAK,QACH,OAAO,iDAAiD,eAAe,UAAU,YAAY;EAC/F,KAAK,aACH,OAAO,yCAAyC,UAAU,WAAW,KAAK,IAAI;CAClF;AACF;AAEA,SAAS,gBACP,WACA,QAC0B;CAC1B,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO;GAAE,YAAY;GAA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,MAAM,CAAC,OAAO,WAAW,UAAU;EACtC,IAAI,MAAM,WAAW,gBAAgB;EACrC,UAAU,IAAI,MAAM,MAAM;GAAE,GAAG,UAAU,IAAI,MAAM,IAAI;GAAG;EAAO,CAAC;CACpE;CACA,OAAO;EAAE;EAAW;CAAc;AACpC","debug_id":"31ad7f34-589c-56f4-b573-e8a5acd1a88a"}
1
+ {"version":3,"file":"package-subgraph-check-BGfeyfnc.mjs","sources":["../src/graphql/package-subgraph-check.ts"],"sourcesContent":["import { typedefs as analyticsTypeDefs } from \"@powerhousedao/analytics-engine-graphql\";\nimport type { DocumentModelGlobalState } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { baseDocumentModels } from \"../packages/base-document-models.js\";\nimport {\n DocumentModelSchemaCache,\n type DocumentModelSource,\n findSubgraphTypeCollisions,\n generatedTypesOf,\n getDocumentModelSubgraphName,\n getGeneratedDocumentModelTypes,\n reservedTypeNames,\n} from \"../utils/create-schema.js\";\nimport authSchema from \"./auth/schema.graphql\";\nimport { inspectionAdminTypeDefs } from \"./inspection/admin-schema.js\";\nimport { inspectionTypeDefs } from \"./inspection/schema.js\";\nimport reactorSchema from \"./reactor/schema.graphql\";\nimport {\n type Admission,\n admitDocumentModels,\n CORE_ORIGIN,\n decideAdmission,\n describeOrigin,\n DOCUMENT_MODEL_ORIGIN,\n documentModelSubgraphSources,\n RegistrationOrder,\n type SubgraphOrigin,\n supergraphClaimLosers,\n} from \"./subgraph-admission.js\";\nimport {\n collectSubgraphClaims,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\nimport { systemTypeDefs } from \"./system/schema.js\";\nimport { DOCUMENT_MODEL_SCHEMA_OWNER } from \"./subgraph-schema-owner.js\";\nimport type {\n PackageSubgraph,\n PackageSubgraphConflicts,\n PackageSubgraphReport,\n RefusedDocumentModel,\n} from \"./subgraph-types.js\";\n\n/** The type definitions of every core subgraph, by subgraph name. */\nexport const coreSubgraphTypeDefs: ReadonlyMap<string, DocumentNode> = new Map([\n [\"analytics\", gql(analyticsTypeDefs)],\n [\"system\", systemTypeDefs],\n [\"r\", gql(reactorSchema)],\n [\"inspection\", inspectionTypeDefs],\n [\"inspection-admin\", inspectionAdminTypeDefs],\n [\"auth\", gql(authSchema)],\n]);\n\nconst PACKAGE_ORIGIN: SubgraphOrigin = \"package\";\n\ntype Registered = {\n name: string;\n origin: SubgraphOrigin;\n typeDefs: DocumentNode;\n ownTypeNames?: ReadonlySet<string>;\n};\n\ntype Rejection = Extract<Admission<Registered>, { action: \"reject\" }>;\n\nfunction claimsOf(typeDefs: DocumentNode, generated: ReadonlySet<string>) {\n try {\n return collectSubgraphClaims(typeDefs, generated);\n } catch {\n // Malformed typeDefs fail where the schema is built, so claim nothing.\n return new Map() as SubgraphClaims;\n }\n}\n\nfunction describeModelSubgraphRejection(rejection: Rejection): string {\n switch (rejection.reason) {\n case \"core name\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(CORE_ORIGIN)}`;\n case \"rank\":\n return `its subgraph name is taken by a subgraph from ${describeOrigin(rejection.holderOrigin)}`;\n case \"collision\":\n return `its subgraph defines generated types: ${rejection.collisions.join(\", \")}`;\n }\n}\n\nfunction packageConflict(\n rejection: Rejection,\n owners: ReadonlyMap<string, string>,\n): PackageSubgraphConflicts {\n switch (rejection.reason) {\n case \"core name\":\n return { nameHeldBy: \"core\", claims: [] };\n case \"rank\":\n return { nameHeldBy: \"document model\", claims: [] };\n case \"collision\":\n return {\n claims: rejection.collisions.map((claim) => ({\n claim,\n owner: owners.get(claim) ?? DOCUMENT_MODEL_SCHEMA_OWNER,\n })),\n };\n }\n}\n\n/** Server admission replayed for one package; hosts and other packages unknown. */\nexport function checkPackageSubgraphs(\n subgraphs: readonly PackageSubgraph[],\n documentModels: readonly DocumentModelGlobalState[],\n): PackageSubgraphReport {\n const packageModels: DocumentModelSource[] = documentModels.map((global) => ({\n documentModel: { global },\n }));\n const { admitted, schemas, refusals } = admitDocumentModels(\n new DocumentModelSchemaCache<DocumentModelSource>().resolve([\n ...baseDocumentModels.map(([, model]) => model),\n ...packageModels,\n ]),\n reservedTypeNames(coreSubgraphTypeDefs.values()),\n );\n const generated = getGeneratedDocumentModelTypes(admitted, schemas);\n const fixed = generatedTypesOf([]).names;\n const generatedOwners = new Map<string, string>();\n for (const model of admitted) {\n const owner = getDocumentModelSubgraphName(model.documentModel.global);\n const { names } = getGeneratedDocumentModelTypes([model], schemas);\n for (const name of names) {\n if (!fixed.has(name)) generatedOwners.set(name, owner);\n }\n }\n\n const holders = new Map<string, Registered>();\n const order = new RegistrationOrder();\n const register = (entry: Registered): Admission<Registered> => {\n const holder = holders.get(entry.name);\n const admission = decideAdmission(\n entry,\n entry.origin,\n holder ? [{ holder, origin: holder.origin }] : [],\n () => {\n try {\n return findSubgraphTypeCollisions(\n generated,\n entry.typeDefs,\n entry.ownTypeNames,\n );\n } catch {\n return [];\n }\n },\n );\n if (admission.action === \"add\") {\n holders.set(entry.name, entry);\n order.record(entry.origin, entry.name);\n }\n return admission;\n };\n\n for (const [name, typeDefs] of coreSubgraphTypeDefs) {\n register({ name, origin: CORE_ORIGIN, typeDefs });\n }\n\n const refusedModels: RefusedDocumentModel[] = refusals\n .filter(({ model }) => packageModels.includes(model))\n .map(({ model, reason, subgraphOnly }) => ({\n name: model.documentModel.global.name,\n reason,\n subgraphOnly,\n }));\n for (const { model, types } of documentModelSubgraphSources(\n admitted,\n schemas,\n )) {\n const admission = register({\n name: getDocumentModelSubgraphName(model.documentModel.global),\n origin: DOCUMENT_MODEL_ORIGIN,\n typeDefs: types.typeDefs,\n ownTypeNames: types.typeNames,\n });\n if (admission.action === \"reject\" && packageModels.includes(model)) {\n refusedModels.push({\n name: model.documentModel.global.name,\n reason: describeModelSubgraphRejection(admission),\n subgraphOnly: true,\n });\n }\n }\n\n const conflicts = new Map<string, PackageSubgraphConflicts>();\n for (const { name, typeDefs } of subgraphs) {\n const admission = register({ name, origin: PACKAGE_ORIGIN, typeDefs });\n if (admission.action === \"reject\") {\n conflicts.set(name, packageConflict(admission, generatedOwners));\n } else if (admission.action === \"add\" && admission.replaces.length > 0) {\n conflicts.set(name, { nameHeldBy: \"package\", claims: [] });\n }\n }\n\n const excluded = supergraphClaimLosers(\n Array.from(holders.values(), (entry) => ({\n member: entry,\n name: entry.name,\n origin: entry.origin,\n claims: claimsOf(entry.typeDefs, generated.names),\n })),\n order,\n );\n for (const [entry, claims] of excluded) {\n if (entry.origin !== PACKAGE_ORIGIN) continue;\n conflicts.set(entry.name, { ...conflicts.get(entry.name), claims });\n }\n return { conflicts, refusedModels };\n}\n"],"names":["analyticsTypeDefs","reactorSchema","authSchema"],"mappings":";;;;;;;;AA4CA,MAAa,uCAA0D,IAAI,IAAI;CAC7E,CAAC,aAAa,IAAIA,QAAiB,CAAC;CACpC,CAAC,UAAU,cAAc;CACzB,CAAC,KAAK,IAAIC,cAAa,CAAC;CACxB,CAAC,cAAc,kBAAkB;CACjC,CAAC,oBAAoB,uBAAuB;CAC5C,CAAC,QAAQ,IAAIC,gBAAU,CAAC;AAC1B,CAAC;AAED,MAAM,iBAAiC;AAWvC,SAAS,SAAS,UAAwB,WAAgC;CACxE,IAAI;EACF,OAAO,sBAAsB,UAAU,SAAS;CAClD,QAAQ;EAEN,uBAAO,IAAI,IAAI;CACjB;AACF;AAEA,SAAS,+BAA+B,WAA8B;CACpE,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO,iDAAiD,eAAe,WAAW;EACpF,KAAK,QACH,OAAO,iDAAiD,eAAe,UAAU,YAAY;EAC/F,KAAK,aACH,OAAO,yCAAyC,UAAU,WAAW,KAAK,IAAI;CAClF;AACF;AAEA,SAAS,gBACP,WACA,QAC0B;CAC1B,QAAQ,UAAU,QAAlB;EACE,KAAK,aACH,OAAO;GAAE,YAAY;GAAQ,QAAQ,CAAC;EAAE;EAC1C,KAAK,QACH,OAAO;GAAE,YAAY;GAAkB,QAAQ,CAAC;EAA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AAM,MAAM;GAAE,GAAG,UAAU,IAAI,MAAM,IAAI;GAAG;EAAO,CAAC;CACpE;CACA,OAAO;EAAE;EAAW;CAAc;AACpC","debug_id":"e70c1355-2855-5f25-92d3-9c6792ff9058"}
@@ -1,13 +1,14 @@
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]="57ca5532-945a-54c2-9b0a-6feb357a7dbd")}catch(e){}}();
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]="b7d7a36c-32db-57bb-9cd6-53a5320d5650")}catch(e){}}();
3
3
  import { o as syncDirectory, s as syncTree, t as fromPGliteErrorInfo } from "./error-info-BaEL50f5.mjs";
4
4
  import { createRequire } from "node:module";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
5
  import { childLogger } from "document-model";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import path from "node:path";
8
8
  import { existsSync, promises } from "node:fs";
9
9
  import { PGlite } from "@electric-sql/pglite";
10
10
  import { NodeFS } from "@electric-sql/pglite/nodefs";
11
+ import v8 from "node:v8";
11
12
  import { Worker } from "node:worker_threads";
12
13
  //#region src/pglite/snapshot-reader.ts
13
14
  const SNAPSHOT_FILE_NAME = "snapshot.bin";
@@ -286,6 +287,17 @@ async function removeStalePgliteFiles(dir, logger) {
286
287
  }
287
288
  }
288
289
  //#endregion
290
+ //#region src/pglite/wasm-wrapper-tiering.ts
291
+ const WASM_WRAPPER_TIERING_FLAG = "--wasm-wrapper-tiering-budget=1000000000";
292
+ let applied = false;
293
+ /** Node 24 V8 double-frees tiered wasm wrappers as instances die (#66366). */
294
+ function disableWasmWrapperTiering() {
295
+ if (applied || process.versions.node.split(".")[0] !== "24") return false;
296
+ v8.setFlagsFromString(WASM_WRAPPER_TIERING_FLAG);
297
+ applied = true;
298
+ return true;
299
+ }
300
+ //#endregion
289
301
  //#region src/pglite/worker/errors.ts
290
302
  /** Base class for failures of the worker itself, as opposed to SQL errors. */
291
303
  var PGliteWorkerError = class extends Error {
@@ -379,6 +391,7 @@ var ThreadedPGlite = class {
379
391
  const memoryLimitMb = options.memoryLimitMb ?? resolvePgliteWorkerMemoryMb(process.env);
380
392
  const workerScript = options.workerScript ?? pgliteWorkerEntryPath;
381
393
  if (workerScript === null) throw new Error("No PGlite worker script is available: build @powerhousedao/reactor-api or pass workerScript");
394
+ disableWasmWrapperTiering();
382
395
  this.worker = new Worker(workerScript, {
383
396
  name: `pglite:${this.label}`,
384
397
  resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb }
@@ -696,7 +709,7 @@ function fileUrlToPath(url) {
696
709
  /** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */
697
710
  const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();
698
711
  //#endregion
699
- export { SNAPSHOT_FILE_NAME as _, resolvePgliteWorkerMemoryMb as a, PGliteWorkerError as c, CURRENT_PGLITE_MAJOR as d, openCurrentPgliteForVerify as f, recoverConversion as g, convertSnapshotDir as h, pgliteWorkerEntryPath as i, PGliteWorkerExitedError as l, removeStalePgliteFiles as m, DEFAULT_PGLITE_WORKER_MEMORY_MB as n, CURRENT_PGLITE_MODULE as o, preparePgliteDataDir as p, ThreadedPGlite as r, PGliteWorkerClosedError as s, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS as t, PGliteWorkerInitError as u, extractSnapshot as v };
712
+ export { convertSnapshotDir as _, resolvePgliteWorkerMemoryMb as a, extractSnapshot as b, PGliteWorkerError as c, WASM_WRAPPER_TIERING_FLAG as d, disableWasmWrapperTiering as f, removeStalePgliteFiles as g, preparePgliteDataDir as h, pgliteWorkerEntryPath as i, PGliteWorkerExitedError as l, openCurrentPgliteForVerify as m, DEFAULT_PGLITE_WORKER_MEMORY_MB as n, CURRENT_PGLITE_MODULE as o, CURRENT_PGLITE_MAJOR as p, ThreadedPGlite as r, PGliteWorkerClosedError as s, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS as t, PGliteWorkerInitError as u, recoverConversion as v, SNAPSHOT_FILE_NAME as y };
700
713
 
701
- //# sourceMappingURL=pglite-node-DOFZDYCK.mjs.map
702
- //# debugId=57ca5532-945a-54c2-9b0a-6feb357a7dbd
714
+ //# sourceMappingURL=pglite-node-DGms6Ssa.mjs.map
715
+ //# debugId=b7d7a36c-32db-57bb-9cd6-53a5320d5650
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-node-DGms6Ssa.mjs","sources":["../src/pglite/snapshot-reader.ts","../src/pglite/convert-snapshot-dir.ts","../src/pglite/preflight.ts","../src/pglite/wasm-wrapper-tiering.ts","../src/pglite/worker/errors.ts","../src/pglite/worker/protocol.ts","../src/pglite/worker/threaded-pglite.ts"],"sourcesContent":["import { promises as fs } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\n// v1: magic, u32 version, u32 count; then u8 type, u32 mode, path, u32 len, data.\nexport const SNAPSHOT_FILE_NAME = \"snapshot.bin\";\nconst MAGIC = new Uint8Array([0x50, 0x47, 0x4c, 0x41]);\nconst FORMAT_VERSION = 1;\nconst HEADER_SIZE = 12;\nconst ENTRY_PREFIX_SIZE = 9;\nconst SKIPPED_ENTRIES = new Set([\"postmaster.pid\"]);\n// Node rejects a single read above 2^31-1 bytes.\nconst DEFAULT_IO_CHUNK_SIZE = 64 * 1024 * 1024;\n\nexport interface ExtractSnapshotOptions {\n chunkSize?: number;\n /** Default true: one fsync pass over the tree after the last write. */\n sync?: boolean;\n hostFs?: SyncTreeHostFs;\n}\n\nexport interface ExtractedSnapshot {\n pgVersionMajor: number;\n /** `global/pg_control` bytes; absent only in synthetic trees. */\n pgControl?: Buffer;\n /** Entries written to disk; skipped entries are not counted. */\n entries: number;\n /** Size of the snapshot file. */\n bytes: number;\n}\n\n/** Unpacks a snapshot into the existing `outDir`. */\nexport async function extractSnapshot(\n snapshotPath: string,\n outDir: string,\n options: ExtractSnapshotOptions = {},\n): Promise<ExtractedSnapshot> {\n const fh = await fs.open(snapshotPath, \"r\");\n try {\n const { size } = await fh.stat();\n return await extractFromHandle(fh, size, outDir, options);\n } finally {\n await fh.close();\n }\n}\n\nasync function extractFromHandle(\n fh: FileHandle,\n fileSize: number,\n outDir: string,\n options: ExtractSnapshotOptions,\n): Promise<ExtractedSnapshot> {\n const root = path.resolve(outDir);\n const chunkSize = Math.min(\n options.chunkSize ?? DEFAULT_IO_CHUNK_SIZE,\n Math.max(1, fileSize),\n );\n const reader = new ChunkedReader(fh, chunkSize);\n\n const header = await reader.take(HEADER_SIZE);\n for (let i = 0; i < MAGIC.length; i++) {\n if (header[i] !== MAGIC[i]) {\n throw new Error(\"snapshot.bin: invalid snapshot magic\");\n }\n }\n const version = header.readUInt32LE(4);\n if (version !== FORMAT_VERSION) {\n throw new Error(`snapshot.bin: unsupported snapshot version ${version}`);\n }\n const count = header.readUInt32LE(8);\n\n const decoder = new TextDecoder();\n let pgVersionText: string | undefined;\n let pgControl: Buffer | undefined;\n let written = 0;\n\n for (let i = 0; i < count; i++) {\n const prefix = await reader.take(ENTRY_PREFIX_SIZE);\n const type = prefix.readUInt8(0);\n const mode = prefix.readUInt32LE(1) & 0o7777;\n const pathLen = prefix.readUInt32LE(5);\n const relPath = decoder.decode(await reader.take(pathLen));\n const dataLen = (await reader.take(4)).readUInt32LE(0);\n const data = await reader.take(dataLen);\n\n const full = resolveInside(root, relPath);\n if (SKIPPED_ENTRIES.has(relPath)) continue;\n\n if (type === 0) {\n await fs.mkdir(full, { recursive: true });\n await fs.chmod(full, dirMode(mode));\n } else if (type === 1) {\n await fs.mkdir(path.dirname(full), { recursive: true });\n await fs.writeFile(full, data);\n await fs.chmod(full, mode);\n if (relPath === \"PG_VERSION\") pgVersionText = data.toString(\"utf8\");\n if (relPath === \"global/pg_control\") pgControl = data;\n } else {\n throw new Error(`snapshot.bin: unknown entry type ${type}`);\n }\n written++;\n }\n\n if (pgVersionText === undefined) {\n throw new Error(\"snapshot.bin: no PG_VERSION entry\");\n }\n const pgVersionMajor = Number.parseInt(pgVersionText.trim(), 10);\n if (!Number.isInteger(pgVersionMajor) || pgVersionMajor <= 0) {\n throw new Error(\n `snapshot.bin: unreadable PG_VERSION ${JSON.stringify(pgVersionText)}`,\n );\n }\n\n if (options.sync ?? true) syncTree(root, options.hostFs);\n\n return { pgVersionMajor, pgControl, entries: written, bytes: fileSize };\n}\n\nfunction resolveInside(root: string, relPath: string): string {\n const full = path.resolve(root, relPath);\n if (full !== root && !full.startsWith(root + path.sep)) {\n throw new Error(`snapshot.bin: entry escapes the data dir: ${relPath}`);\n }\n return full;\n}\n\n/** NTFS has no execute bit; a Windows snapshot can carry untraversable dirs. */\nexport function dirMode(mode: number): number {\n return (mode & 0o7777) | 0o111;\n}\n\nclass ChunkedReader {\n private readonly buf: Buffer;\n private start = 0;\n private end = 0;\n private position = 0;\n\n constructor(\n private readonly fh: Pick<FileHandle, \"read\">,\n chunkSize: number,\n ) {\n this.buf = Buffer.allocUnsafe(Math.max(1, chunkSize));\n }\n\n async take(n: number): Promise<Buffer> {\n const out = Buffer.allocUnsafe(n);\n let filled = 0;\n while (filled < n) {\n if (this.start === this.end) {\n if (n - filled >= this.buf.byteLength) {\n filled += await this.readInto(out, filled, n - filled);\n continue;\n }\n this.start = 0;\n this.end = await this.readInto(this.buf, 0, this.buf.byteLength);\n }\n const k = Math.min(this.end - this.start, n - filled);\n this.buf.copy(out, filled, this.start, this.start + k);\n this.start += k;\n filled += k;\n }\n return out;\n }\n\n private async readInto(\n target: Buffer,\n offset: number,\n length: number,\n ): Promise<number> {\n const { bytesRead } = await this.fh.read(\n target,\n offset,\n Math.min(length, this.buf.byteLength),\n this.position,\n );\n if (bytesRead <= 0) {\n throw new Error(\"snapshot.bin: truncated snapshot\");\n }\n this.position += bytesRead;\n return bytesRead;\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { extractSnapshot, SNAPSHOT_FILE_NAME } from \"./snapshot-reader.js\";\nimport { syncDirectory, syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\nexport interface VerifyHandle {\n query<T>(sql: string): Promise<{ rows: T[] }>;\n close(): Promise<void>;\n}\n\nexport type ConversionStep =\n | \"extract\"\n | \"verify\"\n | \"renameOld\"\n | \"renameNew\"\n | \"removeOld\";\n\nexport interface ConversionDeps {\n /** Opens `dataDir` with the stock NodeFS of the PGlite module for `major`. */\n openForVerify: (major: number, dataDir: string) => Promise<VerifyHandle>;\n logger: ILogger;\n /** Test hook: throw after a named step to simulate a crash there. */\n afterStep?: (step: ConversionStep) => void | Promise<void>;\n hostFs?: SyncTreeHostFs;\n}\n\n// Backoff doubles per retry; five keeps a scanner-held file to ~3 s.\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n} as const;\n\ninterface Siblings {\n dir: string;\n converting: string;\n old: string;\n snapshot: string;\n}\n\nfunction siblingsOf(dir: string): Siblings {\n const resolved = path.resolve(dir);\n return {\n dir: resolved,\n converting: `${resolved}.converting`,\n old: `${resolved}.old`,\n snapshot: path.join(resolved, SNAPSHOT_FILE_NAME),\n };\n}\n\n/** Settles the debris of an interrupted conversion; runs before it at boot. */\nexport async function recoverConversion(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n const s = siblingsOf(dir);\n const [dirExists, convertingExists, oldExists] = await Promise.all([\n exists(s.dir),\n exists(s.converting),\n exists(s.old),\n ]);\n\n if (!dirExists) {\n if (convertingExists) {\n // Died between the two renames: finish the swap.\n await fs.rename(s.converting, s.dir);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n deps.logger.warn(\n `PGlite conversion of ${s.dir} was interrupted after the swap started; completed it`,\n );\n return;\n }\n if (oldExists) {\n throw new Error(\n `PGlite data dir ${s.dir} is missing but ${s.old} exists; refusing to initialize beside it. Inspect and rename or remove ${s.old}.`,\n );\n }\n return;\n }\n\n const snapshotExists = await exists(s.snapshot);\n if (snapshotExists) {\n // The snapshot is authoritative; anything beside it is debris.\n if (convertingExists) await fs.rm(s.converting, RM_OPTIONS);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n return;\n }\n\n // dir is a converted PGDATA; anything beside it is superseded.\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n if (convertingExists) {\n deps.logger.warn(\n `Removing stray ${s.converting}; ${s.dir} holds no snapshot and is authoritative`,\n );\n await fs.rm(s.converting, RM_OPTIONS);\n }\n}\n\n/** Extracts into `.converting`, verifies by opening it, swaps through `.old`. */\nexport async function convertSnapshotDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<\"converted\" | \"none\"> {\n const s = siblingsOf(dir);\n if (!(await exists(s.snapshot))) return \"none\";\n\n const startedAt = performance.now();\n await fs.rm(s.converting, RM_OPTIONS);\n await fs.mkdir(s.converting, { mode: 0o700 });\n\n let snapshotBytes: number;\n let entries: number;\n try {\n ({ bytes: snapshotBytes, entries } = await extractAndVerify(s, deps));\n } catch (err) {\n await fs.rm(s.converting, RM_OPTIONS);\n throw err;\n }\n\n // Parent synced after each rename: a power loss lands on one recovery row.\n const parent = path.dirname(s.dir);\n await fs.rename(s.dir, s.old);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameOld\");\n await fs.rename(s.converting, s.dir);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameNew\");\n try {\n await fs.rm(s.old, RM_OPTIONS);\n } catch (err) {\n // The converted dir is in place; recoverConversion removes .old next boot.\n deps.logger.warn(\n `Could not remove ${s.old} after conversion; it is removed at the next boot: ${String(err)}`,\n );\n }\n await deps.afterStep?.(\"removeOld\");\n\n const convertedBytes = await treeBytes(s.dir);\n const durationMs = Math.round(performance.now() - startedAt);\n deps.logger.info(\n `Converted PGlite snapshot at ${s.dir}: snapshot ${snapshotBytes} bytes -> ${convertedBytes} bytes on disk, ${entries} entries, ${durationMs} ms`,\n );\n return \"converted\";\n}\n\nasync function extractAndVerify(\n s: Siblings,\n deps: ConversionDeps,\n): Promise<{ bytes: number; entries: number }> {\n const extracted = await extractSnapshot(s.snapshot, s.converting, {\n sync: false,\n });\n await deps.afterStep?.(\"extract\");\n\n if (!extracted.pgControl) {\n throw new Error(`${s.snapshot} has no global/pg_control entry`);\n }\n const expectedIdentifier = extracted.pgControl.readBigUInt64LE(0).toString();\n const handle = await deps.openForVerify(\n extracted.pgVersionMajor,\n s.converting,\n );\n try {\n await verifyOpenStore(handle, expectedIdentifier);\n } finally {\n // Must close before the renames; Windows refuses to rename an open dir.\n await handle.close();\n }\n await fs.rm(path.join(s.converting, \"postmaster.pid\"), { force: true });\n if (await exists(path.join(s.converting, SNAPSHOT_FILE_NAME))) {\n throw new Error(\n `Extracted PGlite data dir ${s.converting} contains ${SNAPSHOT_FILE_NAME}`,\n );\n }\n // One pass covers the extraction and the verify open's own writes.\n syncTree(s.converting, deps.hostFs);\n await deps.afterStep?.(\"verify\");\n return { bytes: extracted.bytes, entries: extracted.entries };\n}\n\nasync function verifyOpenStore(\n handle: VerifyHandle,\n expectedIdentifier: string,\n): Promise<void> {\n // numeric parses to a float above 2^53; compare as text.\n const ident = await handle.query<{ system_identifier: string }>(\n \"SELECT system_identifier::text AS system_identifier FROM pg_control_system()\",\n );\n const actual = ident.rows[0]?.system_identifier;\n if (actual !== expectedIdentifier) {\n throw new Error(\n `PGlite system identifier mismatch after extraction: pg_control says ${expectedIdentifier}, server says ${String(actual)}`,\n );\n }\n const tables = await handle.query<{ qualified: string }>(\n \"SELECT format('%I.%I', schemaname, tablename) AS qualified FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema') ORDER BY 1\",\n );\n for (const { qualified } of tables.rows) {\n await handle.query(`SELECT count(*) FROM ${qualified}`);\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.lstat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function treeBytes(dir: string): Promise<number> {\n let total = 0;\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await treeBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n","import { PGlite } from \"@electric-sql/pglite\";\nimport { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n convertSnapshotDir,\n recoverConversion,\n type ConversionDeps,\n type VerifyHandle,\n} from \"./convert-snapshot-dir.js\";\n\n/** PG major of the pinned @electric-sql/pglite; it exports none, so the test checks initdb. */\nexport const CURRENT_PGLITE_MAJOR = 17;\n\n/** `openForVerify` over the loaded PGlite module only. */\nexport async function openCurrentPgliteForVerify(\n major: number,\n dataDir: string,\n): Promise<VerifyHandle> {\n if (major !== CURRENT_PGLITE_MAJOR) {\n throw new Error(\n `PGlite snapshot at ${dataDir} is PG${major}; this process only opens PG${CURRENT_PGLITE_MAJOR} data dirs`,\n );\n }\n const pg = new PGlite({ fs: new NodeFS(dataDir) });\n await pg.waitReady;\n return pg;\n}\n\n/** Converts a snapshot store and clears the files a previous run leaves behind. */\nexport async function preparePgliteDataDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n await recoverConversion(dir, deps);\n await convertSnapshotDir(dir, deps);\n await removeStalePgliteFiles(dir, deps.logger);\n}\n\n/** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */\nexport async function removeStalePgliteFiles(\n dir: string,\n logger: Pick<ILogger, \"debug\">,\n): Promise<void> {\n const lockfile = path.join(dir, \"postmaster.pid\");\n let hadLockfile = true;\n try {\n await fs.unlink(lockfile);\n } catch {\n hadLockfile = false;\n }\n if (hadLockfile) logger.debug(`Removed PGlite lockfile ${lockfile}`);\n\n const walDir = path.join(dir, \"pg_wal\");\n let names: string[];\n try {\n names = await fs.readdir(walDir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.startsWith(\"xlogtemp.\")) continue;\n await fs.rm(path.join(walDir, name), { force: true });\n logger.debug(`Removed PGlite temp WAL file ${path.join(walDir, name)}`);\n }\n}\n","import v8 from \"node:v8\";\n\nexport const WASM_WRAPPER_TIERING_FLAG =\n \"--wasm-wrapper-tiering-budget=1000000000\";\n\nlet applied = false;\n\n/** Node 24 V8 double-frees tiered wasm wrappers as instances die (#66366). */\nexport function disableWasmWrapperTiering(): boolean {\n // TODO(nodejs/node#66376): narrow to 24.x releases older than the backport.\n if (applied || process.versions.node.split(\".\")[0] !== \"24\") return false;\n v8.setFlagsFromString(WASM_WRAPPER_TIERING_FLAG);\n applied = true;\n return true;\n}\n","/** Base class for failures of the worker itself, as opposed to SQL errors. */\nexport class PGliteWorkerError extends Error {\n constructor(\n readonly label: string,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"PGliteWorkerError\";\n }\n}\n\n/** The worker could not open its store; every call on the stand-in fails with this. */\nexport class PGliteWorkerInitError extends PGliteWorkerError {\n constructor(label: string, options?: { cause?: unknown }) {\n super(\n label,\n `PGlite worker for ${label} failed to open its store`,\n options,\n );\n this.name = \"PGliteWorkerInitError\";\n }\n}\n\n/** The worker thread exited (crash, terminate, out of memory) before answering. */\nexport class PGliteWorkerExitedError extends PGliteWorkerError {\n constructor(\n label: string,\n readonly exitCode: number,\n options?: { cause?: unknown },\n ) {\n super(\n label,\n `PGlite worker for ${label} exited with code ${exitCode}`,\n options,\n );\n this.name = \"PGliteWorkerExitedError\";\n }\n}\n\n/** A call was made after `close()` started. */\nexport class PGliteWorkerClosedError extends PGliteWorkerError {\n constructor(label: string) {\n super(label, `PGlite worker for ${label} is closed`);\n this.name = \"PGliteWorkerClosedError\";\n }\n}\n","/**\n * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread\n * and the worker thread that owns one PGlite store.\n *\n * Every payload is structured-cloned, so it holds data only: functions such as\n * row parsers are named by preset and built inside the worker.\n */\n\n/** Module specifiers the worker imports PGlite and its NodeFS from. */\nexport type PGliteModuleSpec = {\n /** Specifier or file URL of the PGlite package entry, e.g. `@electric-sql/pglite`. */\n pglite: string;\n /** Specifier or file URL of the matching NodeFS entry, e.g. `@electric-sql/pglite/nodefs`. */\n nodefs: string;\n};\n\nexport const CURRENT_PGLITE_MODULE: PGliteModuleSpec = {\n pglite: \"@electric-sql/pglite\",\n nodefs: \"@electric-sql/pglite/nodefs\",\n};\n\n/** Row parser sets the worker knows how to build. */\nexport type PGliteParserPreset = \"none\" | \"utc-timestamps\";\n\n/** DurableNodeFs settings; see `DurableNodeFsOptions`. */\nexport type PGliteWorkerDurableFsOptions = {\n fsync: boolean;\n /** Undefined keeps the DurableNodeFs default (5 min); 0 disables. */\n maintenanceIntervalMs?: number;\n /** Undefined keeps the DurableNodeFs default (256 MB); 0 disables. */\n vacuumFullAboveBytes?: number;\n /** Undefined keeps the DurableNodeFs default (60 s); 0 runs VACUUM FULL on the first pass. */\n vacuumFullQuietMs?: number;\n /** Undefined keeps the DurableNodeFs default (0: the quiet window only); a deadline in ms forces the run past it. */\n vacuumFullMaxDeferMs?: number;\n};\n\n/** What the worker opens. */\nexport type PGliteWorkerStoreOptions = {\n /** Names the store in logs and errors, e.g. `read-storage`. */\n label: string;\n /** PGlite data dir; null opens an in-memory store. */\n dataDir: string | null;\n module: PGliteModuleSpec;\n /** DurableNodeFs over `dataDir`; null uses the module's stock NodeFS. Ignored in memory. */\n durableFs: PGliteWorkerDurableFsOptions | null;\n parsers: PGliteParserPreset;\n};\n\n/** The structured-clonable subset of PGlite's `QueryOptions`. */\nexport type WorkerQueryOptions = {\n rowMode?: \"object\" | \"array\";\n paramTypes?: number[];\n};\n\nexport type PGliteErrorInfo = {\n name: string;\n message: string;\n stack?: string;\n cause?: PGliteErrorInfo;\n /** Postgres error fields, copied when present. */\n fields: Record<string, string>;\n};\n\nexport type WorkerResults = {\n rows: unknown[];\n affectedRows?: number;\n fields: { name: string; dataTypeID: number }[];\n};\n\nexport type InitRequest = {\n type: \"init\";\n id: number;\n store: PGliteWorkerStoreOptions;\n};\n\nexport type QueryRequest = {\n type: \"query\";\n id: number;\n /** The reservation this statement runs under, or null for the request queue. */\n admission: number | null;\n sql: string;\n params: unknown[];\n options: WorkerQueryOptions;\n};\n\nexport type ExecRequest = {\n type: \"exec\";\n id: number;\n admission: number | null;\n sql: string;\n options: WorkerQueryOptions;\n};\n\nexport type CloseRequest = {\n type: \"close\";\n id: number;\n};\n\n/**\n * Asks for the connection: answered with `admitted` once everything queued\n * ahead (requests and maintenance passes) has finished. Until the matching\n * `release`, the worker runs only statements tagged with this reservation.\n */\nexport type ReserveRequest = {\n type: \"reserve\";\n id: number;\n};\n\n/** Ends a reservation; the request queue resumes. Not answered. */\nexport type ReleaseRequest = {\n type: \"release\";\n id: number;\n};\n\nexport type HostMessage =\n | InitRequest\n | QueryRequest\n | ExecRequest\n | CloseRequest\n | ReserveRequest\n | ReleaseRequest;\n\nexport type AdmittedMessage = {\n type: \"admitted\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type ReadyMessage = {\n type: \"ready\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type QueryResultMessage = {\n type: \"query-result\";\n id: number;\n result: WorkerResults;\n inTransaction: boolean;\n};\n\nexport type ExecResultMessage = {\n type: \"exec-result\";\n id: number;\n results: WorkerResults[];\n inTransaction: boolean;\n};\n\nexport type ClosedMessage = {\n type: \"closed\";\n id: number;\n};\n\nexport type ErrorMessage = {\n type: \"error\";\n id: number;\n error: PGliteErrorInfo;\n inTransaction: boolean;\n};\n\n/** The wasm runtime aborted (a Postgres PANIC); the store is dead. */\nexport type AbortMessage = {\n type: \"abort\";\n reason: string;\n};\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type LogMessage = {\n type: \"log\";\n level: LogLevel;\n message: string;\n error?: PGliteErrorInfo;\n};\n\nexport type WorkerMessage =\n | AdmittedMessage\n | ReadyMessage\n | QueryResultMessage\n | ExecResultMessage\n | ClosedMessage\n | ErrorMessage\n | AbortMessage\n | LogMessage;\n","import type { QueryOptions, Results } from \"@electric-sql/pglite\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { Worker, type ResourceLimits } from \"node:worker_threads\";\nimport type { PGliteLike } from \"../pglite-like.js\";\nimport { disableWasmWrapperTiering } from \"../wasm-wrapper-tiering.js\";\nimport { fromPGliteErrorInfo } from \"./error-info.js\";\nimport {\n PGliteWorkerClosedError,\n PGliteWorkerExitedError,\n PGliteWorkerInitError,\n} from \"./errors.js\";\nimport type {\n HostMessage,\n LogMessage,\n PGliteWorkerStoreOptions,\n WorkerMessage,\n WorkerQueryOptions,\n WorkerResults,\n} from \"./protocol.js\";\n\nexport const DEFAULT_PGLITE_WORKER_MEMORY_MB = 1024;\nexport const DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS = 60_000;\n\nexport type ThreadedPGliteOptions = {\n store: PGliteWorkerStoreOptions;\n /** Caps the worker's JS heap; defaults to {@link resolvePgliteWorkerMemoryMb}. WebAssembly memory is outside it. */\n memoryLimitMb?: number;\n /** The worker script; defaults to the built entry next to this module. Tests pass a tsx bootstrap. */\n workerScript?: string | URL;\n /** Bound on PGlite's own close (its shutdown checkpoint) before the thread is terminated. */\n closeGraceMs?: number;\n logger?: ILogger;\n};\n\n/** Called once, when the worker reports that the wasm runtime aborted. */\nexport type PGliteAbortListener = (reason: string) => void;\n\n/** Called once, when the worker thread is gone; `error` is null after a clean close. */\nexport type PGliteExitListener = (error: Error | null) => void;\n\ntype PendingKind = \"init\" | \"query\" | \"exec\" | \"close\" | \"reserve\";\n\ntype Pending = {\n kind: PendingKind;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n};\n\ntype Phase = \"starting\" | \"ready\" | \"closing\" | \"closed\";\n\n/** `PH_PGLITE_WORKER_MEMORY_MB`, else {@link DEFAULT_PGLITE_WORKER_MEMORY_MB}. */\nexport function resolvePgliteWorkerMemoryMb(\n env: Record<string, string | undefined>,\n): number {\n const raw = env.PH_PGLITE_WORKER_MEMORY_MB;\n if (raw === undefined || raw.trim() === \"\") {\n return DEFAULT_PGLITE_WORKER_MEMORY_MB;\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\n `PH_PGLITE_WORKER_MEMORY_MB must be a positive integer (got: ${raw})`,\n );\n }\n return parsed;\n}\n\n/**\n * Main-thread stand-in for a PGlite instance whose store lives in a worker\n * thread. It has the surface knex-pglite, kysely-pglite-dialect and\n * `HardenedPGliteDialect` use: `waitReady`, `query`, `exec`, a synchronous\n * `isInTransaction()`, `closed` and `close()`.\n *\n * Construction is synchronous and starts the worker; calls made before the\n * worker is ready are queued behind its open. The worker runs requests one at\n * a time in arrival order, and every answer carries the transaction status.\n * The instance is a plain extensible object, since knex stores its own\n * bookkeeping on the connection.\n */\nexport class ThreadedPGlite implements PGliteLike {\n readonly label: string;\n /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */\n readonly waitReady: Promise<void>;\n\n private readonly worker: Worker;\n private readonly logger: ILogger;\n private readonly closeGraceMs: number;\n private readonly pending = new Map<number, Pending>();\n /** The reservation an `admit` run is executing under, carried through its async calls. */\n private readonly admission = new AsyncLocalStorage<number>();\n private readonly abortListeners = new Set<PGliteAbortListener>();\n private readonly exitListeners = new Set<PGliteExitListener>();\n private nextId = 1;\n private phase: Phase = \"starting\";\n private inTransaction = false;\n private terminalError: Error | null = null;\n private workerError: Error | null = null;\n private abortReason: string | null = null;\n private closePromise: Promise<void> | null = null;\n\n constructor(options: ThreadedPGliteOptions) {\n this.label = options.store.label;\n this.logger =\n options.logger ??\n childLogger([\"reactor-api\", \"pglite-worker\", this.label]);\n this.closeGraceMs =\n options.closeGraceMs ?? DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS;\n const memoryLimitMb =\n options.memoryLimitMb ?? resolvePgliteWorkerMemoryMb(process.env);\n\n const workerScript = options.workerScript ?? pgliteWorkerEntryPath;\n if (workerScript === null) {\n throw new Error(\n \"No PGlite worker script is available: build @powerhousedao/reactor-api or pass workerScript\",\n );\n }\n disableWasmWrapperTiering();\n this.worker = new Worker(workerScript, {\n name: `pglite:${this.label}`,\n resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb },\n });\n this.worker.on(\"message\", (msg: WorkerMessage) => this.handleMessage(msg));\n this.worker.on(\"error\", (err: Error) => this.handleWorkerError(err));\n this.worker.on(\"exit\", (code: number) => this.handleExit(code));\n\n this.waitReady = this.request<void>(\"init\", (id) => ({\n type: \"init\",\n id,\n store: options.store,\n })).then(\n () => {\n if (this.phase === \"starting\") {\n this.phase = \"ready\";\n }\n },\n (error: unknown) => {\n const initError =\n error instanceof PGliteWorkerInitError\n ? error\n : new PGliteWorkerInitError(this.label, { cause: error });\n this.fail(initError);\n throw initError;\n },\n );\n this.waitReady.catch(() => undefined);\n }\n\n /** True once the store is open and until close starts. */\n get ready(): boolean {\n return this.phase === \"ready\";\n }\n\n /** True once close has started or the worker is gone. */\n get closed(): boolean {\n return this.phase === \"closing\" || this.phase === \"closed\";\n }\n\n /** The reason the worker reported for a wasm abort, or null. */\n get aborted(): string | null {\n return this.abortReason;\n }\n\n /** The limits the worker thread runs under (empty once it has exited). */\n get resourceLimits(): ResourceLimits {\n return this.worker.resourceLimits ?? {};\n }\n\n /** The worker's thread id, for diagnostics. */\n get threadId(): number {\n return this.worker.threadId;\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n const wireOptions = toWireOptions(options);\n const result = await this.request<WorkerResults>(\"query\", (id) => ({\n type: \"query\",\n id,\n admission: this.currentAdmission(),\n sql,\n params: params ?? [],\n options: wireOptions,\n }));\n return toResults<T>(result);\n }\n\n async exec(sql: string, options?: QueryOptions): Promise<Results[]> {\n const wireOptions = toWireOptions(options);\n const results = await this.request<WorkerResults[]>(\"exec\", (id) => ({\n type: \"exec\",\n id,\n admission: this.currentAdmission(),\n sql,\n options: wireOptions,\n }));\n return results.map((result) => toResults(result));\n }\n\n /**\n * `HardenedPGliteDialect`'s admission hook: `run` starts only once the worker\n * can run its statements at once, with nothing queued ahead and no\n * maintenance pass in progress, so the dialect's statement deadline (which\n * starts inside `run`) never counts time spent waiting behind other work.\n * Statements `run` issues bypass the queue until it settles; everything\n * else waits behind them.\n */\n async admit<T>(run: () => Promise<T>): Promise<T> {\n let reservation = 0;\n await this.request<void>(\"reserve\", (id) => {\n reservation = id;\n return { type: \"reserve\", id };\n });\n try {\n return await this.admission.run(reservation, run);\n } finally {\n this.release(reservation);\n }\n }\n\n /** The status after the most recently answered request, as PGlite reported it. */\n isInTransaction(): boolean {\n return this.inTransaction;\n }\n\n /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */\n close(): Promise<void> {\n if (this.closePromise !== null) {\n return this.closePromise;\n }\n if (this.phase === \"closed\") {\n return Promise.resolve();\n }\n this.closePromise = this.closeWorker();\n return this.closePromise;\n }\n\n /** Stops the thread at once, without PGlite's close; pending calls reject. */\n async terminate(): Promise<void> {\n if (this.phase === \"closed\") {\n return;\n }\n await this.worker.terminate();\n }\n\n onAbort(listener: PGliteAbortListener): () => void {\n this.abortListeners.add(listener);\n return () => {\n this.abortListeners.delete(listener);\n };\n }\n\n onExit(listener: PGliteExitListener): () => void {\n this.exitListeners.add(listener);\n return () => {\n this.exitListeners.delete(listener);\n };\n }\n\n private async closeWorker(): Promise<void> {\n if (this.terminalError !== null) {\n this.phase = \"closing\";\n await this.worker.terminate();\n return;\n }\n const closing = this.request<void>(\"close\", (id) => ({\n type: \"close\",\n id,\n }));\n this.phase = \"closing\";\n let timer: ReturnType<typeof setTimeout> | undefined;\n const grace = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), this.closeGraceMs);\n });\n let outcome: \"closed\" | \"timeout\" = \"closed\";\n let closeError: Error | null = null;\n try {\n outcome = await Promise.race([\n closing.then(() => \"closed\" as const),\n grace,\n ]);\n } catch (error) {\n closeError = error instanceof Error ? error : new Error(String(error));\n } finally {\n clearTimeout(timer);\n }\n if (outcome === \"timeout\") {\n this.logger.warn(\n `PGlite worker for ${this.label} did not close within ${this.closeGraceMs}ms; terminating`,\n );\n }\n await this.worker.terminate();\n if (closeError !== null) {\n throw closeError;\n }\n }\n\n private currentAdmission(): number | null {\n return this.admission.getStore() ?? null;\n }\n\n private release(reservation: number): void {\n if (this.phase === \"closed\") {\n return;\n }\n const message: HostMessage = { type: \"release\", id: reservation };\n this.worker.postMessage(message);\n }\n\n private request<T>(\n kind: PendingKind,\n build: (id: number) => HostMessage,\n ): Promise<T> {\n if (this.terminalError !== null) {\n return Promise.reject(this.terminalError);\n }\n if (kind !== \"init\" && this.closed) {\n return Promise.reject(new PGliteWorkerClosedError(this.label));\n }\n const id = this.nextId++;\n const promise = new Promise<T>((resolve, reject) => {\n this.pending.set(id, {\n kind,\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n });\n this.worker.postMessage(build(id));\n return promise;\n }\n\n private handleMessage(msg: WorkerMessage): void {\n switch (msg.type) {\n case \"admitted\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"ready\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"query-result\":\n this.settle(msg.id, msg.inTransaction, msg.result);\n return;\n case \"exec-result\":\n this.settle(msg.id, msg.inTransaction, msg.results);\n return;\n case \"closed\":\n this.settle(msg.id, false, undefined);\n return;\n case \"error\":\n this.settleError(\n msg.id,\n msg.inTransaction,\n fromPGliteErrorInfo(msg.error),\n );\n return;\n case \"abort\":\n this.handleAbort(msg.reason);\n return;\n case \"log\":\n this.handleLog(msg);\n return;\n default: {\n const exhaustive: never = msg;\n void exhaustive;\n }\n }\n }\n\n private settle(id: number, inTransaction: boolean, value: unknown): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.resolve(value);\n }\n\n private settleError(id: number, inTransaction: boolean, error: Error): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.reject(error);\n }\n\n private handleAbort(reason: string): void {\n if (this.abortReason !== null) {\n return;\n }\n this.abortReason = reason;\n this.logger.error(\n `PGlite worker for ${this.label} aborted: @reason`,\n reason,\n );\n for (const listener of [...this.abortListeners]) {\n try {\n listener(reason);\n } catch (error) {\n this.logger.error(\"PGlite abort listener threw: @error\", error);\n }\n }\n }\n\n private handleLog(msg: LogMessage): void {\n const message = `[${this.label}] ${msg.message}`;\n const args =\n msg.error === undefined ? [] : [fromPGliteErrorInfo(msg.error)];\n const template = args.length > 0 ? `${message}: @error` : message;\n switch (msg.level) {\n case \"debug\":\n this.logger.debug(template, ...args);\n return;\n case \"info\":\n this.logger.info(template, ...args);\n return;\n case \"warn\":\n this.logger.warn(template, ...args);\n return;\n case \"error\":\n this.logger.error(template, ...args);\n return;\n default: {\n const exhaustive: never = msg.level;\n void exhaustive;\n }\n }\n }\n\n private handleWorkerError(err: Error): void {\n this.workerError = err;\n this.logger.error(`PGlite worker for ${this.label} failed: @error`, err);\n }\n\n private handleExit(code: number): void {\n const graceful = this.phase === \"closing\" && this.terminalError === null;\n this.phase = \"closed\";\n this.inTransaction = false;\n const error = graceful\n ? null\n : (this.terminalError ??\n new PGliteWorkerExitedError(this.label, code, {\n cause: this.workerError ?? undefined,\n }));\n if (error !== null && this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error ?? new PGliteWorkerClosedError(this.label));\n for (const listener of [...this.exitListeners]) {\n try {\n listener(error);\n } catch (listenerError) {\n this.logger.error(\"PGlite exit listener threw: @error\", listenerError);\n }\n }\n this.exitListeners.clear();\n this.abortListeners.clear();\n }\n\n /** Records a fatal error and stops the thread; the exit rejects what is pending. */\n private fail(error: Error): void {\n if (this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error);\n void this.worker.terminate();\n }\n\n private rejectPending(error: Error): void {\n const entries = [...this.pending.values()];\n this.pending.clear();\n for (const entry of entries) {\n entry.reject(error);\n }\n }\n}\n\nfunction toWireOptions(options: QueryOptions | undefined): WorkerQueryOptions {\n if (options === undefined) {\n return {};\n }\n if (\n options.parsers !== undefined ||\n options.serializers !== undefined ||\n options.blob !== undefined ||\n options.onNotice !== undefined\n ) {\n throw new Error(\n \"ThreadedPGlite does not support parsers, serializers, blob or onNotice per query; configure parsers on the worker\",\n );\n }\n const wire: WorkerQueryOptions = {};\n if (options.rowMode !== undefined) {\n wire.rowMode = options.rowMode;\n }\n if (options.paramTypes !== undefined) {\n wire.paramTypes = options.paramTypes;\n }\n return wire;\n}\n\nfunction toResults<T>(result: WorkerResults): Results<T> {\n const out: Results<T> = {\n rows: result.rows as T[],\n fields: result.fields,\n };\n if (result.affectedRows !== undefined) {\n out.affectedRows = result.affectedRows;\n }\n return out;\n}\n\n/**\n * The worker script: the built entry (chunking may place this module in\n * `dist/` or `dist/src/pglite/`), or, when this module runs from its\n * TypeScript source, a bootstrap that loads the entry through tsx. Null when\n * neither is available.\n */\nfunction resolvePgliteWorkerEntryPath(): string | null {\n if (/\\.m?ts$/.test(new URL(import.meta.url).pathname)) {\n return resolveSourceBootstrap();\n }\n const candidates = [\n \"./src/pglite/worker/entry.mjs\",\n \"./worker/entry.mjs\",\n \"./entry.mjs\",\n ].map((relative) => fileUrlToPath(new URL(relative, import.meta.url)));\n return candidates.find((candidate) => existsSync(candidate)) ?? null;\n}\n\nfunction resolveSourceBootstrap(): string | null {\n const bootstrap = fileUrlToPath(\n new URL(\"./source-bootstrap.mjs\", import.meta.url),\n );\n if (!existsSync(bootstrap)) {\n return null;\n }\n try {\n createRequire(import.meta.url).resolve(\"tsx/esm/api\");\n } catch {\n return null;\n }\n return bootstrap;\n}\n\nfunction fileUrlToPath(url: URL): string {\n if (url.protocol !== \"file:\") {\n return url.href;\n }\n let pathname = decodeURIComponent(url.pathname);\n if (/^\\/[A-Za-z]:[/\\\\]/.test(pathname)) {\n pathname = pathname.slice(1);\n }\n return pathname;\n}\n\n/** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */\nexport const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();\n"],"names":["fs","fs","fs"],"mappings":";;;;;;;;;;;;;AAMA,MAAa,qBAAqB;AAClC,MAAM,QAAQ,IAAI,WAAW;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC;AACrD,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,oBAAoB;AAC1B,MAAM,kCAAkB,IAAI,IAAI,CAAC,gBAAgB,CAAC;AAElD,MAAM,wBAAwB;;AAoB9B,eAAsB,gBACpB,cACA,QACA,UAAkC,CAAC,GACP;CAC5B,MAAM,KAAK,MAAMA,SAAG,KAAK,cAAc,GAAG;CAC1C,IAAI;EACF,MAAM,EAAE,SAAS,MAAM,GAAG,KAAK;EAC/B,OAAO,MAAM,kBAAkB,IAAI,MAAM,QAAQ,OAAO;CAC1D,UAAU;EACR,MAAM,GAAG,MAAM;CACjB;AACF;AAEA,eAAe,kBACb,IACA,UACA,QACA,SAC4B;CAC5B,MAAM,OAAO,KAAK,QAAQ,MAAM;CAKhC,MAAM,SAAS,IAAI,cAAc,IAJf,KAAK,IACrB,QAAQ,aAAa,uBACrB,KAAK,IAAI,GAAG,QAAQ,CAEe,CAAS;CAE9C,MAAM,SAAS,MAAM,OAAO,KAAK,WAAW;CAC5C,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,IAAI,OAAO,OAAO,MAAM,IACtB,MAAM,IAAI,MAAM,sCAAsC;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,WAAW,SAAS,GACvB,OAAO;CAET,IAAI;EACF,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,aAAa;CACtD,QAAQ;EACN,OAAO;CACT;CACA,OAAO;AACT;AAEA,SAAS,cAAc,KAAkB;CACvC,IAAI,IAAI,aAAa,SACnB,OAAO,IAAI;CAEb,IAAI,WAAW,mBAAmB,IAAI,QAAQ;CAC9C,IAAI,oBAAoB,KAAK,QAAQ,GACnC,WAAW,SAAS,MAAM,CAAC;CAE7B,OAAO;AACT;;AAGA,MAAa,wBAAwB,6BAA6B","debug_id":"b7d7a36c-32db-57bb-9cd6-53a5320d5650"}
@@ -4,7 +4,7 @@ import { t as DOCUMENT_MODEL_SCHEMA_OWNER } from "../../subgraph-schema-owner-BE
4
4
  //#region src/graphql/subgraph-types.ts
5
5
  /** Loaded on call: the check pulls in the base models and core schemas. */
6
6
  async function findPackageSubgraphConflicts(subgraphs, documentModels) {
7
- const { checkPackageSubgraphs } = await import("../../package-subgraph-check-6tK9LMg1.mjs");
7
+ const { checkPackageSubgraphs } = await import("../../package-subgraph-check-BGfeyfnc.mjs");
8
8
  return checkPackageSubgraphs(subgraphs, documentModels);
9
9
  }
10
10
  //#endregion
@@ -1,6 +1,6 @@
1
- import { d as ReportError, o as ISubscribablePackageLoader, s as ISubscriptionOptions, u as PackagePieceEntry } from "../../types-CCI5IDgT.mjs";
2
- import { DocumentModelModule, UpgradeManifest } from "@powerhousedao/shared/document-model";
1
+ import { d as ReportError, o as ISubscribablePackageLoader, s as ISubscriptionOptions, u as PackagePieceEntry } from "../../types-BEpxtyKW.mjs";
3
2
  import { ILogger } from "document-model";
3
+ import { DocumentModelModule, UpgradeManifest } from "@powerhousedao/shared/document-model";
4
4
  import { Logger, ViteDevServer } from "vite";
5
5
  import { ProcessorFactoryBuilder, SubgraphClass } from "@powerhousedao/reactor-api";
6
6
  //#region src/packages/vite-loader.d.mts
@@ -1 +1 @@
1
- {"version":3,"file":"vite-loader.d.mts","names":[],"sources":["../../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AaZ,eACE,oBACA,UAAU,QAAQ,8BAClB,UAAU;;;;;;;;wBA4BE,2BAA2B,gBAAY;wBAqBjC,gBAAgB,cAAc,SAAS,SAAM,QAAA"}
@@ -1,9 +1,10 @@
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]="90f792c4-97fb-52c4-91c3-8f6a5b0d178b")}catch(e){}}();
3
- import { _ as PACKAGE_MODULE_FAILED, a as packageRootOf, b as isSubpath, c as piecesFromListModule, g as runDetached, l as extractDocumentModels, n as BUILT_PIECE_LIST, o as pieceListLocation, r as PIECES_SUBPATH, t as extractSubgraphs, v as debounce, y as extractUpgradeManifests } from "../../subgraph-extraction-zUDn2zX_.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]="7fddc8fd-c47a-5c99-868c-56ad2bd6b899")}catch(e){}}();
3
+ import { _ as PACKAGE_MODULE_FAILED, a as packageRootOf, b as isSubpath, c as piecesFromListModule, g as runDetached, l as extractDocumentModels, n as BUILT_PIECE_LIST, o as pieceListLocation, r as PIECES_SUBPATH, t as extractSubgraphs, v as debounce, y as extractUpgradeManifests } from "../../subgraph-extraction-BYKOycxo.mjs";
4
4
  import { childLogger } from "document-model";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
+ import { getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
7
8
  import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
8
9
  import { readPackage } from "read-pkg";
9
10
  import { createLogger, createServer } from "vite";
@@ -142,17 +143,22 @@ var VitePackageLoader = class VitePackageLoader {
142
143
  this.logger.debug(` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`);
143
144
  return pieces;
144
145
  }
145
- #watch(label, matches, load, handler, options) {
146
+ #watch(label, reported, matches, load, handler, options) {
146
147
  let subscribed = true;
148
+ const report = (failure) => getCodegenStatusRegistry().reportLoad(reported.pkg, reported.kind, failure);
147
149
  const reloadOnce = debounce(() => runDetached(label, async () => {
148
150
  if (!subscribed) return;
149
151
  let value;
150
152
  try {
151
153
  value = await load();
152
154
  } catch (e) {
153
- if (e.code === "ERR_PACKAGE_MODULE_FAILED") return;
155
+ if (e.code === "ERR_PACKAGE_MODULE_FAILED") {
156
+ report(`[${this.name}] ${e.message}`);
157
+ return;
158
+ }
154
159
  throw e;
155
160
  }
161
+ report();
156
162
  if (subscribed) handler(value);
157
163
  }, {
158
164
  logger: this.logger,
@@ -174,21 +180,33 @@ var VitePackageLoader = class VitePackageLoader {
174
180
  }
175
181
  onDocumentModelsChange(identifier, handler, options) {
176
182
  const documentModelsPath = this.getDocumentModelsPath(identifier);
177
- return this.#watch(`Reloading the document models of ${identifier}`, (changedPath) => isSubpath(documentModelsPath, changedPath), () => this.loadDocumentModels(identifier), handler, options);
183
+ return this.#watch(`Reloading the document models of ${identifier}`, {
184
+ pkg: identifier,
185
+ kind: "document models"
186
+ }, (changedPath) => isSubpath(documentModelsPath, changedPath), () => this.loadDocumentModels(identifier), handler, options);
178
187
  }
179
188
  onSubgraphsChange(identifier, handler, options) {
180
189
  const subgraphsPath = this.getSubgraphsPath(identifier);
181
- return this.#watch(`Reloading the subgraphs of ${identifier}`, (changedPath) => isSubpath(subgraphsPath, changedPath), () => this.loadSubgraphs(identifier), handler, options);
190
+ return this.#watch(`Reloading the subgraphs of ${identifier}`, {
191
+ pkg: identifier,
192
+ kind: "subgraphs"
193
+ }, (changedPath) => isSubpath(subgraphsPath, changedPath), () => this.loadSubgraphs(identifier), handler, options);
182
194
  }
183
195
  onProcessorsChange(identifier, handler, options) {
184
196
  const processorsPath = this.getProcessorsPath(identifier);
185
- return this.#watch(`Reloading the processors of ${identifier}`, (changedPath) => isSubpath(processorsPath, changedPath), () => this.loadProcessors(identifier), handler, options);
197
+ return this.#watch(`Reloading the processors of ${identifier}`, {
198
+ pkg: identifier,
199
+ kind: "processors"
200
+ }, (changedPath) => isSubpath(processorsPath, changedPath), () => this.loadProcessors(identifier), handler, options);
186
201
  }
187
202
  onPiecesChange(identifier, handler, options) {
188
203
  const watched = [this.getPiecesPath(identifier)];
189
204
  const root = this.pieceRoot(identifier);
190
205
  if (root !== void 0) watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));
191
- return this.#watch(`Reloading the pieces of ${identifier}`, (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)), () => this.loadPieces(identifier), handler, options);
206
+ return this.#watch(`Reloading the pieces of ${identifier}`, {
207
+ pkg: identifier,
208
+ kind: "pieces"
209
+ }, (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)), () => this.loadPieces(identifier), handler, options);
192
210
  }
193
211
  };
194
212
  const toSlashes = (file) => file.replaceAll("\\", "/");
@@ -213,10 +231,11 @@ async function startViteServer(root, logger) {
213
231
  return await createServer({
214
232
  root,
215
233
  configFile: false,
216
- logger,
234
+ customLogger: logger,
217
235
  server: {
218
236
  middlewareMode: true,
219
237
  hmr: false,
238
+ ws: false,
220
239
  watch: { ignored: ["**/.ph/**", ignoreBuildOutputButPieces(root)] }
221
240
  },
222
241
  appType: "custom",
@@ -243,4 +262,4 @@ async function startViteServer(root, logger) {
243
262
  export { VitePackageLoader, createViteLogger, ignoreBuildOutputButPieces, startViteServer };
244
263
 
245
264
  //# sourceMappingURL=vite-loader.mjs.map
246
- //# debugId=90f792c4-97fb-52c4-91c3-8f6a5b0d178b
265
+ //# debugId=7fddc8fd-c47a-5c99-868c-56ad2bd6b899
@@ -1 +1 @@
1
- {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { extractDocumentModels } from \"./document-model-detection.js\";\nimport { extractSubgraphs } from \"./subgraph-extraction.js\";\nimport {\n BUILT_PIECE_LIST,\n PIECES_SUBPATH,\n packageRootOf,\n pieceListLocation,\n piecesFromListModule,\n} from \"./pieces.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n PackagePieceEntry,\n} from \"./types.js\";\nimport {\n PACKAGE_MODULE_FAILED,\n debounce,\n extractUpgradeManifests,\n isSubpath,\n} from \"./util.js\";\nimport { runDetached, type ReportError } from \"../utils/detached.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport interface VitePackageLoaderOptions {\n /** Modules, as paths or file URLs, whose dependencies a package the project\n * does not install may resolve from. This loader's own module always is. */\n resolveFrom?: string[];\n reportError?: ReportError;\n}\n\ninterface LoadedModule {\n id: string;\n namespace: Record<string, unknown>;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n private readonly importers: string[];\n\n readonly #reportError?: ReportError;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer, options?: VitePackageLoaderOptions) {\n return new VitePackageLoader(vite, options);\n }\n\n constructor(vite: ViteDevServer, options: VitePackageLoaderOptions = {}) {\n this.vite = vite;\n this.importers = [...(options.resolveFrom ?? []), import.meta.url].map(\n (from) => (from.startsWith(\"file:\") ? fileURLToPath(from) : from),\n );\n this.#reportError = options.reportError;\n }\n\n // The project first, then the host's own dependencies. A bare name or a path\n // Vite cannot resolve is a package without that module, not an error.\n async #resolve(identifier: string, subpath: string) {\n const aliased = path.isAbsolute(identifier)\n ? undefined\n : this.aliasedRoot(identifier);\n const specifier = path.posix.join(aliased ?? identifier, subpath);\n const bare = !aliased && !path.isAbsolute(identifier);\n const importers = bare ? [undefined, ...this.importers] : [undefined];\n const container = this.vite.environments.ssr.pluginContainer;\n for (const importer of importers) {\n try {\n const resolved = await container.resolveId(specifier, importer);\n if (resolved && !resolved.external) return resolved.id;\n } catch (e) {\n this.logger.debug(\"Could not resolve @specifier: @error\", specifier, e);\n }\n }\n return undefined;\n }\n\n // Resolved before it is loaded, so only a module that exists and fails is\n // reported and thrown; one a package does not have is a debug-level miss.\n async #load(\n identifier: string,\n subpath: string,\n ): Promise<LoadedModule | undefined> {\n const id = await this.#resolve(identifier, subpath);\n if (id === undefined) {\n this.logger.debug(\"No @subpath module in @pkg\", subpath, identifier);\n return undefined;\n }\n try {\n const namespace = (await this.vite.ssrLoadModule(id)) as Record<\n string,\n unknown\n >;\n return { id, namespace };\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n this.logger.error(\n \"Failed to load @subpath of @pkg from @id: @error\",\n subpath,\n identifier,\n id,\n message,\n );\n // Tagged: vite's own code can read as a package without the module.\n throw Object.assign(\n new Error(`Failed to load ${id}: ${message}`, { cause: e }),\n { code: PACKAGE_MODULE_FAILED },\n );\n }\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n private getPiecesPath(identifier: string): string {\n return path.posix.join(identifier, `./${PIECES_SUBPATH}`);\n }\n\n // The dev server aliases the local project by its own package name, so a\n // package that is this project is rooted at the source tree vite serves.\n private aliasedRoot(identifier: string): string | undefined {\n const alias = this.vite.config.resolve.alias;\n const entries = Array.isArray(alias) ? alias : [];\n const hit = entries.find((entry) => entry.find === identifier);\n return typeof hit?.replacement === \"string\" ? hit.replacement : undefined;\n }\n\n // What a declared piece path is relative to. Not the module vite loaded: a\n // list read from source still points at the built output beside it.\n private pieceRoot(identifier: string, listId?: string): string | undefined {\n if (!path.isAbsolute(identifier)) {\n const aliased = this.aliasedRoot(identifier);\n if (aliased) return aliased;\n // A built list resolved from wherever the package is installed.\n if (listId) return packageRootOf(path.dirname(listId));\n }\n try {\n return pieceListLocation(identifier).root;\n } catch {\n return undefined;\n }\n }\n\n async loadDocumentModels(identifier: string): Promise<DocumentModelModule[]> {\n this.logger.debug(\n \"Loading document models from\",\n this.getDocumentModelsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"document-models\");\n if (!loaded) return [];\n\n const documentModels = extractDocumentModels(loaded.namespace);\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n return documentModels;\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests.\n for (const subpath of [\n \"document-models\",\n \"document-models/upgrade-manifests\",\n ]) {\n const loaded = await this.#load(identifier, subpath);\n if (!loaded) continue;\n const manifests = extractUpgradeManifests(loaded.namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n this.logger.verbose(\n \"Loading subgraphs from\",\n this.getSubgraphsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"subgraphs\");\n if (!loaded) return [];\n\n const subgraphs = extractSubgraphs(loaded.namespace);\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n this.logger.verbose(\n \"Loading processors from\",\n this.getProcessorsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"processors\");\n const factory = loaded?.namespace.processorFactory;\n if (typeof factory === \"function\") {\n this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);\n return factory as ProcessorFactoryBuilder;\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n return null;\n }\n\n // The list only, never a piece: in dev it is usually the TypeScript source,\n // and what it names is still the built bundle a worker will load.\n async loadPieces(identifier: string): Promise<PackagePieceEntry[]> {\n this.logger.verbose(\"Loading pieces from\", this.getPiecesPath(identifier));\n const loaded = await this.#load(identifier, PIECES_SUBPATH);\n if (!loaded) return [];\n\n const root = this.pieceRoot(identifier, loaded.id);\n if (root === undefined) {\n this.logger.debug(` ➜ No package root found for: ${identifier}`);\n return [];\n }\n\n const pieces = piecesFromListModule(loaded.namespace, {\n root,\n identifier,\n logger: this.logger,\n });\n this.logger.debug(\n ` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`,\n );\n return pieces;\n }\n\n // One detached reload per burst of file events. \"add\" and \"unlink\" too, or a\n // removed entry never reports empty and its registrations leak. Once\n // unsubscribed, no pending or running reload reaches `handler`, and a\n // failed load leaves the last good set.\n #watch<T>(\n label: string,\n matches: (changedPath: string) => unknown,\n load: () => Promise<T>,\n handler: (value: T) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n let subscribed = true;\n const reloadOnce = debounce(\n () =>\n runDetached(\n label,\n async () => {\n if (!subscribed) return;\n let value: T;\n try {\n value = await load();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === PACKAGE_MODULE_FAILED) {\n return;\n }\n throw e;\n }\n if (subscribed) handler(value);\n },\n { logger: this.logger, report: this.#reportError },\n ),\n options?.debounce ?? 100,\n );\n const listener = (changedPath: string) => {\n if (matches(changedPath)) void reloadOnce();\n };\n const events = [\"change\", \"add\", \"unlink\"] as const;\n for (const event of events) this.vite.watcher.on(event, listener);\n\n return () => {\n subscribed = false;\n for (const event of events) this.vite.watcher.off(event, listener);\n };\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n return this.#watch(\n `Reloading the document models of ${identifier}`,\n (changedPath) => isSubpath(documentModelsPath, changedPath),\n () => this.loadDocumentModels(identifier),\n handler,\n options,\n );\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n return this.#watch(\n `Reloading the subgraphs of ${identifier}`,\n (changedPath) => isSubpath(subgraphsPath, changedPath),\n () => this.loadSubgraphs(identifier),\n handler,\n options,\n );\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n return this.#watch(\n `Reloading the processors of ${identifier}`,\n (changedPath) => isSubpath(processorsPath, changedPath),\n () => this.loadProcessors(identifier),\n handler,\n options,\n );\n }\n\n onPiecesChange(\n identifier: string,\n handler: (pieces: PackagePieceEntry[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n // Both the source list and the build output: the list says which pieces a\n // package ships, and only the build decides whether one is there to run.\n const watched = [this.getPiecesPath(identifier)];\n const root = this.pieceRoot(identifier);\n if (root !== undefined) {\n watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n }\n return this.#watch(\n `Reloading the pieces of ${identifier}`,\n (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)),\n () => this.loadPieces(identifier),\n handler,\n options,\n );\n }\n}\n\nconst toSlashes = (file: string) => file.replaceAll(\"\\\\\", \"/\");\n\n/**\n * The project's build output, but for the built piece list `onPiecesChange`\n * watches: its own `dist/` and a Tauri shell's Rust `target/`. On Windows\n * every watched file costs a synchronous `fs.watch` at startup, over a\n * minute for a built project with a built desktop shell.\n */\nexport function ignoreBuildOutputButPieces(root: string) {\n const dist = `${toSlashes(path.resolve(root, \"dist\"))}/`;\n const pieces = toSlashes(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n return (file: string) => {\n const at = toSlashes(path.resolve(root, file));\n if (\n at.includes(\"/tauri-shell/target/\") ||\n at.includes(\"/src-tauri/target/\")\n ) {\n return true;\n }\n if (!at.startsWith(dist)) return false;\n // The piece list's folder, what is in it, and the folders leading to it stay watched.\n return !(\n at === pieces ||\n at.startsWith(`${pieces}/`) ||\n pieces.startsWith(`${at}/`)\n );\n };\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: {\n middlewareMode: true,\n // It loads modules, never serves a page: no HMR port to collide on.\n hmr: false,\n watch: { ignored: [\"**/.ph/**\", ignoreBuildOutputButPieces(root)] },\n },\n appType: \"custom\",\n // Its own cache, and no client deps to optimize: Studio's cache is the\n // project's node_modules/.vite, which it would otherwise rewrite.\n cacheDir: path.join(root, \"node_modules\", \".vite-reactor\"),\n optimizeDeps: { noDiscovery: true, include: [], entries: [] },\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAqCA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,OACF,CAAC;CAeD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,SAAS,KAAK,YACzB,SAAS,QACL,OAAO,MAAM,SAAS,KAAK,QAAQ,KAAK,IACxC,OAAO,MAAM,SAAS,GAAG;CAC/B,OAAO;AACT;AAcA,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,eAAe,aAAa,CAAC;CAEpE;CAEA;CAEA;CAEA,OAAgB;CAEhB,OAAO,MAAM,MAAqB,SAAoC;EACpE,OAAO,IAAI,kBAAkB,MAAM,OAAO;CAC5C;CAEA,YAAY,MAAqB,UAAoC,CAAC,GAAG;EACvE,KAAK,OAAO;EACZ,KAAK,YAAY,CAAC,GAAI,QAAQ,eAAe,CAAC,GAAI,YAAY,GAAG,CAAC,CAAC,KAChE,SAAU,KAAK,WAAW,OAAO,IAAI,cAAc,IAAI,IAAI,IAC9D;EACA,KAAK,eAAe,QAAQ;CAC9B;CAIA,MAAM,SAAS,YAAoB,SAAiB;EAClD,MAAM,UAAU,KAAK,WAAW,UAAU,IACtC,KAAA,IACA,KAAK,YAAY,UAAU;EAC/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,MAAc;CACvD,MAAM,OAAO,GAAG,UAAU,KAAK,QAAQ,MAAM,MAAM,CAAC,EAAE;CACtD,MAAM,SAAS,UAAU,KAAK,QAAQ,KAAK,QAAQ,MAAM,gBAAgB,CAAC,CAAC;CAC3E,QAAQ,SAAiB;EACvB,MAAM,KAAK,UAAU,KAAK,QAAQ,MAAM,IAAI,CAAC;EAC7C,IACE,GAAG,SAAS,sBAAsB,KAClC,GAAG,SAAS,oBAAoB,GAEhC,OAAO;EAET,IAAI,CAAC,GAAG,WAAW,IAAI,GAAG,OAAO;EAEjC,OAAO,EACL,OAAO,UACP,GAAG,WAAW,GAAG,OAAO,EAAE,KAC1B,OAAO,WAAW,GAAG,GAAG,EAAE;CAE9B;AACF;AAEA,eAAsB,gBAAgB,MAAc,QAAiB;CACnE,MAAM,cAAc,MAAM,YAAY,EAAE,KAAK,KAAK,CAAC;CAyCnD,OAAO,MAvCY,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GACN,gBAAgB;GAEhB,KAAK;GACL,OAAO,EAAE,SAAS,CAAC,aAAa,2BAA2B,IAAI,CAAC,EAAE;EACpE;EACA,SAAS;EAGT,UAAU,KAAK,KAAK,MAAM,gBAAgB,eAAe;EACzD,cAAc;GAAE,aAAa;GAAM,SAAS,CAAC;GAAG,SAAS,CAAC;EAAE;EAC5D,OAAO,EACL,eAAe,EACb,OAAO,CAAC,EACV,EACF;EACA,SAAS;GACP,eAAe;GACf,OAAO,GACJ,YAAY,OAAO,KACtB;EACF;EACA,SAAS,CAGP,aAAa,GACb;GACE,MAAM;GACN,kBAAkB;IAChB,OAAO,CAAC;GACV;EACF,CACF;CACF,CAAC;AAGH","debug_id":"90f792c4-97fb-52c4-91c3-8f6a5b0d178b"}
1
+ {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { getCodegenStatusRegistry } from \"@powerhousedao/shared/processors\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { extractDocumentModels } from \"./document-model-detection.js\";\nimport { extractSubgraphs } from \"./subgraph-extraction.js\";\nimport {\n BUILT_PIECE_LIST,\n PIECES_SUBPATH,\n packageRootOf,\n pieceListLocation,\n piecesFromListModule,\n} from \"./pieces.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n PackagePieceEntry,\n} from \"./types.js\";\nimport {\n PACKAGE_MODULE_FAILED,\n debounce,\n extractUpgradeManifests,\n isSubpath,\n} from \"./util.js\";\nimport { runDetached, type ReportError } from \"../utils/detached.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport interface VitePackageLoaderOptions {\n /** Modules, as paths or file URLs, whose dependencies a package the project\n * does not install may resolve from. This loader's own module always is. */\n resolveFrom?: string[];\n reportError?: ReportError;\n}\n\ninterface LoadedModule {\n id: string;\n namespace: Record<string, unknown>;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n private readonly importers: string[];\n\n readonly #reportError?: ReportError;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer, options?: VitePackageLoaderOptions) {\n return new VitePackageLoader(vite, options);\n }\n\n constructor(vite: ViteDevServer, options: VitePackageLoaderOptions = {}) {\n this.vite = vite;\n this.importers = [...(options.resolveFrom ?? []), import.meta.url].map(\n (from) => (from.startsWith(\"file:\") ? fileURLToPath(from) : from),\n );\n this.#reportError = options.reportError;\n }\n\n // The project first, then the host's own dependencies. A bare name or a path\n // Vite cannot resolve is a package without that module, not an error.\n async #resolve(identifier: string, subpath: string) {\n const aliased = path.isAbsolute(identifier)\n ? undefined\n : this.aliasedRoot(identifier);\n const specifier = path.posix.join(aliased ?? identifier, subpath);\n const bare = !aliased && !path.isAbsolute(identifier);\n const importers = bare ? [undefined, ...this.importers] : [undefined];\n const container = this.vite.environments.ssr.pluginContainer;\n for (const importer of importers) {\n try {\n const resolved = await container.resolveId(specifier, importer);\n if (resolved && !resolved.external) return resolved.id;\n } catch (e) {\n this.logger.debug(\"Could not resolve @specifier: @error\", specifier, e);\n }\n }\n return undefined;\n }\n\n // Resolved before it is loaded, so only a module that exists and fails is\n // reported and thrown; one a package does not have is a debug-level miss.\n async #load(\n identifier: string,\n subpath: string,\n ): Promise<LoadedModule | undefined> {\n const id = await this.#resolve(identifier, subpath);\n if (id === undefined) {\n this.logger.debug(\"No @subpath module in @pkg\", subpath, identifier);\n return undefined;\n }\n try {\n const namespace = (await this.vite.ssrLoadModule(id)) as Record<\n string,\n unknown\n >;\n return { id, namespace };\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n this.logger.error(\n \"Failed to load @subpath of @pkg from @id: @error\",\n subpath,\n identifier,\n id,\n message,\n );\n // Tagged: vite's own code can read as a package without the module.\n throw Object.assign(\n new Error(`Failed to load ${id}: ${message}`, { cause: e }),\n { code: PACKAGE_MODULE_FAILED },\n );\n }\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n private getPiecesPath(identifier: string): string {\n return path.posix.join(identifier, `./${PIECES_SUBPATH}`);\n }\n\n // The dev server aliases the local project by its own package name, so a\n // package that is this project is rooted at the source tree vite serves.\n private aliasedRoot(identifier: string): string | undefined {\n const alias = this.vite.config.resolve.alias;\n const entries = Array.isArray(alias) ? alias : [];\n const hit = entries.find((entry) => entry.find === identifier);\n return typeof hit?.replacement === \"string\" ? hit.replacement : undefined;\n }\n\n // What a declared piece path is relative to. Not the module vite loaded: a\n // list read from source still points at the built output beside it.\n private pieceRoot(identifier: string, listId?: string): string | undefined {\n if (!path.isAbsolute(identifier)) {\n const aliased = this.aliasedRoot(identifier);\n if (aliased) return aliased;\n // A built list resolved from wherever the package is installed.\n if (listId) return packageRootOf(path.dirname(listId));\n }\n try {\n return pieceListLocation(identifier).root;\n } catch {\n return undefined;\n }\n }\n\n async loadDocumentModels(identifier: string): Promise<DocumentModelModule[]> {\n this.logger.debug(\n \"Loading document models from\",\n this.getDocumentModelsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"document-models\");\n if (!loaded) return [];\n\n const documentModels = extractDocumentModels(loaded.namespace);\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n return documentModels;\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests.\n for (const subpath of [\n \"document-models\",\n \"document-models/upgrade-manifests\",\n ]) {\n const loaded = await this.#load(identifier, subpath);\n if (!loaded) continue;\n const manifests = extractUpgradeManifests(loaded.namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n this.logger.verbose(\n \"Loading subgraphs from\",\n this.getSubgraphsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"subgraphs\");\n if (!loaded) return [];\n\n const subgraphs = extractSubgraphs(loaded.namespace);\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n this.logger.verbose(\n \"Loading processors from\",\n this.getProcessorsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"processors\");\n const factory = loaded?.namespace.processorFactory;\n if (typeof factory === \"function\") {\n this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);\n return factory as ProcessorFactoryBuilder;\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n return null;\n }\n\n // The list only, never a piece: in dev it is usually the TypeScript source,\n // and what it names is still the built bundle a worker will load.\n async loadPieces(identifier: string): Promise<PackagePieceEntry[]> {\n this.logger.verbose(\"Loading pieces from\", this.getPiecesPath(identifier));\n const loaded = await this.#load(identifier, PIECES_SUBPATH);\n if (!loaded) return [];\n\n const root = this.pieceRoot(identifier, loaded.id);\n if (root === undefined) {\n this.logger.debug(` ➜ No package root found for: ${identifier}`);\n return [];\n }\n\n const pieces = piecesFromListModule(loaded.namespace, {\n root,\n identifier,\n logger: this.logger,\n });\n this.logger.debug(\n ` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`,\n );\n return pieces;\n }\n\n // One detached reload per burst of file events. \"add\" and \"unlink\" too, or a\n // removed entry never reports empty and its registrations leak. Once\n // unsubscribed, no pending or running reload reaches `handler`, and a\n // failed load leaves the last good set.\n #watch<T>(\n label: string,\n reported: { pkg: string; kind: string },\n matches: (changedPath: string) => unknown,\n load: () => Promise<T>,\n handler: (value: T) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n let subscribed = true;\n // Read by reactor-mcp's getCodegenStatus, e.g. for broken generated code.\n const report = (failure?: string) =>\n getCodegenStatusRegistry().reportLoad(\n reported.pkg,\n reported.kind,\n failure,\n );\n const reloadOnce = debounce(\n () =>\n runDetached(\n label,\n async () => {\n if (!subscribed) return;\n let value: T;\n try {\n value = await load();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === PACKAGE_MODULE_FAILED) {\n report(`[${this.name}] ${(e as Error).message}`);\n return;\n }\n throw e;\n }\n report();\n if (subscribed) handler(value);\n },\n { logger: this.logger, report: this.#reportError },\n ),\n options?.debounce ?? 100,\n );\n const listener = (changedPath: string) => {\n if (matches(changedPath)) void reloadOnce();\n };\n const events = [\"change\", \"add\", \"unlink\"] as const;\n for (const event of events) this.vite.watcher.on(event, listener);\n\n return () => {\n subscribed = false;\n for (const event of events) this.vite.watcher.off(event, listener);\n };\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n return this.#watch(\n `Reloading the document models of ${identifier}`,\n { pkg: identifier, kind: \"document models\" },\n (changedPath) => isSubpath(documentModelsPath, changedPath),\n () => this.loadDocumentModels(identifier),\n handler,\n options,\n );\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n return this.#watch(\n `Reloading the subgraphs of ${identifier}`,\n { pkg: identifier, kind: \"subgraphs\" },\n (changedPath) => isSubpath(subgraphsPath, changedPath),\n () => this.loadSubgraphs(identifier),\n handler,\n options,\n );\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n return this.#watch(\n `Reloading the processors of ${identifier}`,\n { pkg: identifier, kind: \"processors\" },\n (changedPath) => isSubpath(processorsPath, changedPath),\n () => this.loadProcessors(identifier),\n handler,\n options,\n );\n }\n\n onPiecesChange(\n identifier: string,\n handler: (pieces: PackagePieceEntry[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n // Both the source list and the build output: the list says which pieces a\n // package ships, and only the build decides whether one is there to run.\n const watched = [this.getPiecesPath(identifier)];\n const root = this.pieceRoot(identifier);\n if (root !== undefined) {\n watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n }\n return this.#watch(\n `Reloading the pieces of ${identifier}`,\n { pkg: identifier, kind: \"pieces\" },\n (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)),\n () => this.loadPieces(identifier),\n handler,\n options,\n );\n }\n}\n\nconst toSlashes = (file: string) => file.replaceAll(\"\\\\\", \"/\");\n\n/**\n * The project's build output, but for the built piece list `onPiecesChange`\n * watches: its own `dist/` and a Tauri shell's Rust `target/`. On Windows\n * every watched file costs a synchronous `fs.watch` at startup, over a\n * minute for a built project with a built desktop shell.\n */\nexport function ignoreBuildOutputButPieces(root: string) {\n const dist = `${toSlashes(path.resolve(root, \"dist\"))}/`;\n const pieces = toSlashes(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n return (file: string) => {\n const at = toSlashes(path.resolve(root, file));\n if (\n at.includes(\"/tauri-shell/target/\") ||\n at.includes(\"/src-tauri/target/\")\n ) {\n return true;\n }\n if (!at.startsWith(dist)) return false;\n // The piece list's folder, what is in it, and the folders leading to it stay watched.\n return !(\n at === pieces ||\n at.startsWith(`${pieces}/`) ||\n pieces.startsWith(`${at}/`)\n );\n };\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n customLogger: logger,\n server: {\n middlewareMode: true,\n // It loads modules, never serves a page: no HMR, and no WebSocket port\n // (24678 by default) for a second project's Vetra to collide on.\n hmr: false,\n ws: false,\n watch: { ignored: [\"**/.ph/**\", ignoreBuildOutputButPieces(root)] },\n },\n appType: \"custom\",\n // Its own cache, and no client deps to optimize: Studio's cache is the\n // project's node_modules/.vite, which it would otherwise rewrite.\n cacheDir: path.join(root, \"node_modules\", \".vite-reactor\"),\n optimizeDeps: { noDiscovery: true, include: [], entries: [] },\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAsCA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,OACF,CAAC;CAeD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,SAAS,KAAK,YACzB,SAAS,QACL,OAAO,MAAM,SAAS,KAAK,QAAQ,KAAK,IACxC,OAAO,MAAM,SAAS,GAAG;CAC/B,OAAO;AACT;AAcA,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,eAAe,aAAa,CAAC;CAEpE;CAEA;CAEA;CAEA,OAAgB;CAEhB,OAAO,MAAM,MAAqB,SAAoC;EACpE,OAAO,IAAI,kBAAkB,MAAM,OAAO;CAC5C;C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AAc;EACd,QAAQ;GACN,gBAAgB;GAGhB,KAAK;GACL,IAAI;GACJ,OAAO,EAAE,SAAS,CAAC,aAAa,2BAA2B,IAAI,CAAC,EAAE;EACpE;EACA,SAAS;EAGT,UAAU,KAAK,KAAK,MAAM,gBAAgB,eAAe;EACzD,cAAc;GAAE,aAAa;GAAM,SAAS,CAAC;GAAG,SAAS,CAAC;EAAE;EAC5D,OAAO,EACL,eAAe,EACb,OAAO,CAAC,EACV,EACF;EACA,SAAS;GACP,eAAe;GACf,OAAO,GACJ,YAAY,OAAO,KACtB;EACF;EACA,SAAS,CAGP,aAAa,GACb;GACE,MAAM;GACN,kBAAkB;IAChB,OAAO,CAAC;GACV;EACF,CACF;CACF,CAAC;AAGH","debug_id":"7fddc8fd-c47a-5c99-868c-56ad2bd6b899"}
@@ -203,6 +203,11 @@ export declare function preparePgliteDataDir(dir: string, deps: ConversionDeps):
203
203
  /** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */
204
204
  export declare function removeStalePgliteFiles(dir: string, logger: Pick<ILogger, "debug">): Promise<void>;
205
205
  //#endregion
206
+ //#region src/pglite/wasm-wrapper-tiering.d.ts
207
+ export declare const WASM_WRAPPER_TIERING_FLAG = "--wasm-wrapper-tiering-budget=1000000000";
208
+ /** Node 24 V8 double-frees tiered wasm wrappers as instances die (#66366). */
209
+ export declare function disableWasmWrapperTiering(): boolean;
210
+ //#endregion
206
211
  //#region src/pglite/worker/protocol.d.ts
207
212
  /**
208
213
  * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread
@@ -1 +1 @@
1
- {"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts","../../../src/pglite/worker/protocol.ts","../../../src/pglite/worker/error-info.ts","../../../src/pglite/worker/errors.ts","../../../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UAKA;;UA0BA;UAQA;;;qBAyFG"}
1
+ {"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts","../../../src/pglite/wasm-wrapper-tiering.ts","../../../src/pglite/worker/protocol.ts","../../../src/pglite/worker/error-info.ts","../../../src/pglite/worker/errors.ts","../../../src/pglite/worker/threaded-pglite.ts"],"mappings":";;;;;;;qBAIa;qBACA;qBACA;;;;;;;;qBAQA;;qBAEA;KAGD;UAQK;EACf,KAAK;;EAEL,MAAM;;;KAII,mBAAmB,GAAG,YAAY,QAAQ,OAAO,QAAQ;UAEpD;;EAEf;;EAEA;;;;;;;EAOA;;;;;;EAMA;;;;;;EAMA,OAAO;EACP,SAAS;;EAET;;qBAGW;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAS;MAsBjB;MAIA;EAIJ,MAAM,IAAI,QAAQ,eAAe;EAUjC;;EAMM,QAAQ;EAMR,OAAO,QAAQ;UAKP;UASA;UAoEN;UAoBA;;;;KCnOE,qBAAqB;UAKhB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,kBAAkB;;EAElB;EACA;IAAW,KAAK;IAAwB,MAAM;;;EAE9C,WAAW;EACX,SAAS,YAAY;;KAGX,gBAAgB,aAAa;WAC9B,aAAa;;wBAGR,mBACd,KAAK;;KAMK;;KASA,4BAA4B,KACtC;;;;;;;;;;;;;;;;wBAmBc,yBACd,KAAK,qCACJ;;wBAyGa,oBACd,MAAM,aACN,iBACA,UAAS,uBACR;;;UC3Lc;EACf,UAAU;;UAGK;EACf;EACA;;;wBAIc,SACd,cACA,SAAQ,iBACP;;wBA+Ba,cACd,aACA,SAAQ;;;qBC3CG;UASI;E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;MAKA;;MAKA;;MAKA,kBAAkB;;MAKlB;EAIE,MAAM,IAAI,yBACd,aACA,oBACA,UAAU,eACT,QAAQ,QAAQ;EAab,KAAK,aAAa,UAAU,eAAe,QAAQ;;;;;;;;;EAoBnD,MAAM,GAAG,WAAW,QAAQ,KAAK,QAAQ;;EAc/C;;EAKA,SAAS;;EAYH,aAAa;EAOnB,QAAQ,UAAU;EAOlB,OAAO,UAAU;UAOH;UAsCN;UAIA;UAQA;UAsBA;UAqCA;UAUA;UAUA;UAkBA;UAyBA;UAKA;;UA0BA;UAQA;;;qBAyFG"}
@@ -1,5 +1,5 @@
1
1
  import { a as resolvePgliteMaintenance, c as DEFAULT_MAINTENANCE_INTERVAL_MS, d as DEFAULT_VACUUM_FULL_QUIET_MS, f as FORCED_VACUUM_FULL_MAX_DEFER_MS, i as resolvePgliteFsync, l as DEFAULT_VACUUM_FULL_ABOVE_BYTES, m as PGLITE_UTC_PARSERS, n as toPGliteErrorInfo, o as syncDirectory, p as PgliteMaintenance, r as createDurableNodeFs, s as syncTree, t as fromPGliteErrorInfo, u as DEFAULT_VACUUM_FULL_MAX_DEFER_MS } from "../../error-info-BaEL50f5.mjs";
2
- import { _ as SNAPSHOT_FILE_NAME, a as resolvePgliteWorkerMemoryMb, c as PGliteWorkerError, d as CURRENT_PGLITE_MAJOR, f as openCurrentPgliteForVerify, g as recoverConversion, h as convertSnapshotDir, i as pgliteWorkerEntryPath, l as PGliteWorkerExitedError, m as removeStalePgliteFiles, n as DEFAULT_PGLITE_WORKER_MEMORY_MB, o as CURRENT_PGLITE_MODULE, p as preparePgliteDataDir, r as ThreadedPGlite, s as PGliteWorkerClosedError, t as DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, u as PGliteWorkerInitError, v as extractSnapshot } from "../../pglite-node-DOFZDYCK.mjs";
3
- export { CURRENT_PGLITE_MAJOR, CURRENT_PGLITE_MODULE, DEFAULT_MAINTENANCE_INTERVAL_MS, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, DEFAULT_PGLITE_WORKER_MEMORY_MB, DEFAULT_VACUUM_FULL_ABOVE_BYTES, DEFAULT_VACUUM_FULL_MAX_DEFER_MS, DEFAULT_VACUUM_FULL_QUIET_MS, FORCED_VACUUM_FULL_MAX_DEFER_MS, PGLITE_UTC_PARSERS, PGliteWorkerClosedError, PGliteWorkerError, PGliteWorkerExitedError, PGliteWorkerInitError, PgliteMaintenance, SNAPSHOT_FILE_NAME, ThreadedPGlite, convertSnapshotDir, createDurableNodeFs, extractSnapshot, fromPGliteErrorInfo, openCurrentPgliteForVerify, pgliteWorkerEntryPath, preparePgliteDataDir, recoverConversion, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteMaintenance, resolvePgliteWorkerMemoryMb, syncDirectory, syncTree, toPGliteErrorInfo };
4
- !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]="11040c0f-dbae-552f-b3da-ed6962737d64")}catch(e){}}();
5
- //# debugId=11040c0f-dbae-552f-b3da-ed6962737d64
2
+ import { _ as convertSnapshotDir, a as resolvePgliteWorkerMemoryMb, b as extractSnapshot, c as PGliteWorkerError, d as WASM_WRAPPER_TIERING_FLAG, f as disableWasmWrapperTiering, g as removeStalePgliteFiles, h as preparePgliteDataDir, i as pgliteWorkerEntryPath, l as PGliteWorkerExitedError, m as openCurrentPgliteForVerify, n as DEFAULT_PGLITE_WORKER_MEMORY_MB, o as CURRENT_PGLITE_MODULE, p as CURRENT_PGLITE_MAJOR, r as ThreadedPGlite, s as PGliteWorkerClosedError, t as DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, u as PGliteWorkerInitError, v as recoverConversion, y as SNAPSHOT_FILE_NAME } from "../../pglite-node-DGms6Ssa.mjs";
3
+ export { CURRENT_PGLITE_MAJOR, CURRENT_PGLITE_MODULE, DEFAULT_MAINTENANCE_INTERVAL_MS, DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS, DEFAULT_PGLITE_WORKER_MEMORY_MB, DEFAULT_VACUUM_FULL_ABOVE_BYTES, DEFAULT_VACUUM_FULL_MAX_DEFER_MS, DEFAULT_VACUUM_FULL_QUIET_MS, FORCED_VACUUM_FULL_MAX_DEFER_MS, PGLITE_UTC_PARSERS, PGliteWorkerClosedError, PGliteWorkerError, PGliteWorkerExitedError, PGliteWorkerInitError, PgliteMaintenance, SNAPSHOT_FILE_NAME, ThreadedPGlite, WASM_WRAPPER_TIERING_FLAG, convertSnapshotDir, createDurableNodeFs, disableWasmWrapperTiering, extractSnapshot, fromPGliteErrorInfo, openCurrentPgliteForVerify, pgliteWorkerEntryPath, preparePgliteDataDir, recoverConversion, removeStalePgliteFiles, resolvePgliteFsync, resolvePgliteMaintenance, resolvePgliteWorkerMemoryMb, syncDirectory, syncTree, toPGliteErrorInfo };
4
+ !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]="a5b1cd7a-ad0f-553e-a374-f8e7c53e2ff9")}catch(e){}}();
5
+ //# debugId=a5b1cd7a-ad0f-553e-a374-f8e7c53e2ff9
@@ -1,13 +1,13 @@
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]="871fe81d-1f96-5056-99a5-af64f77ff138")}catch(e){}}();
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]="60bff0fd-90c1-5fac-ab7d-2a49e4b9f4c3")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
+ import { childLogger } from "document-model";
4
5
  import { gql } from "graphql-tag";
5
6
  import { GraphQLError } from "graphql";
6
7
  import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
7
8
  import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
8
9
  import { verifyAuthBearerToken } from "@renown/sdk";
9
10
  import { AsyncLocalStorage } from "node:async_hooks";
10
- import { childLogger } from "document-model";
11
11
  import path, { dirname, isAbsolute, join } from "node:path";
12
12
  import { existsSync, readFileSync } from "node:fs";
13
13
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -844,6 +844,20 @@ var BaseSubgraph = class {
844
844
  async canReadDocument(documentId, ctx) {
845
845
  return this.authorizationService.canRead(documentId, ctx.user?.address);
846
846
  }
847
+ /** The ids or slugs in `ids` that {@link assertCanRead} admits, in order; the rest are dropped. */
848
+ async filterReadableDocumentIds(ids, ctx) {
849
+ const readable = [];
850
+ for (const id of ids) {
851
+ try {
852
+ await this.assertCanRead(id, ctx);
853
+ } catch (error) {
854
+ if (error instanceof ForbiddenError) continue;
855
+ throw error;
856
+ }
857
+ readable.push(id);
858
+ }
859
+ return readable;
860
+ }
847
861
  /** Drops the items the host's own ACL refuses the caller. */
848
862
  async readableByHost(items, ctx) {
849
863
  if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return [...items];
@@ -1399,5 +1413,5 @@ function extractSubgraphs(namespace) {
1399
1413
  //#endregion
1400
1414
  export { CanonicalDocumentIdResolutionError as A, loadSubgraphs as C, RequestClientBinder as D, callerSubject as E, AuthEvaluationUnsupportedError as F, AuthenticationRequiredError as I, ForbiddenError as L, AuthorizationPolicy as M, AuthorizedDocumentHandle as N, AuthService as O, createAuthorizationService as P, MalformedStoredOperationError as R, loadProcessors as S, BaseSubgraph as T, PACKAGE_MODULE_FAILED as _, packageRootOf as a, isSubpath as b, piecesFromListModule as c, buildGraphQlDriveDocument as d, buildGraphqlOperation as f, runDetached as g, reportFailure as h, PIECE_SOURCE_LIST as i, createCanonicalDocumentIdResolver as j, createCredentialInvalidator as k, extractDocumentModels as l, isSubgraphClass as m, BUILT_PIECE_LIST as n, pieceListLocation as o, buildGraphqlOperations as p, PIECES_SUBPATH as r, piecesFromCdnList as s, extractSubgraphs as t, buildGraphQlDocument as u, debounce as v, manifestDeclaredSubgraphs as w, loadDocumentModels as x, extractUpgradeManifests as y, RefusalNotRecordedError as z };
1401
1415
 
1402
- //# sourceMappingURL=subgraph-extraction-zUDn2zX_.mjs.map
1403
- //# debugId=871fe81d-1f96-5056-99a5-af64f77ff138
1416
+ //# sourceMappingURL=subgraph-extraction-BYKOycxo.mjs.map
1417
+ //# debugId=60bff0fd-90c1-5fac-ab7d-2a49e4b9f4c3