@powerhousedao/reactor-api 6.2.3-dev.75 → 6.2.3-dev.77
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{base-document-models-BGt__Ctn.mjs → base-document-models-Dh70m9Bh.mjs} +4 -4
- package/dist/{base-document-models-BGt__Ctn.mjs.map → base-document-models-Dh70m9Bh.mjs.map} +1 -1
- package/dist/index.d.mts +205 -11
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +656 -285
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-C5S8yvBI.mjs → package-subgraph-check-DhCWO3YR.mjs} +4 -4
- package/dist/{package-subgraph-check-C5S8yvBI.mjs.map → package-subgraph-check-DhCWO3YR.mjs.map} +1 -1
- package/dist/{pglite-node-BOFT_yUj.mjs → pglite-node-BMux5A2Y.mjs} +4 -4
- package/dist/{pglite-node-BOFT_yUj.mjs.map → pglite-node-BMux5A2Y.mjs.map} +1 -1
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/packages/vite-loader.mjs +1 -1
- package/dist/src/pglite/pglite-node.mjs +3 -3
- package/dist/{subgraph-extraction-cSpPp3Hq.mjs → subgraph-extraction-zUDn2zX_.mjs} +239 -13
- package/dist/subgraph-extraction-zUDn2zX_.mjs.map +1 -0
- package/package.json +13 -13
- package/dist/subgraph-extraction-cSpPp3Hq.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]="
|
|
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-
|
|
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]="dc6d029a-6550-58ef-a415-304bf5e56dbf")}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-Dh70m9Bh.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-
|
|
138
|
-
//# debugId=
|
|
137
|
+
//# sourceMappingURL=package-subgraph-check-DhCWO3YR.mjs.map
|
|
138
|
+
//# debugId=dc6d029a-6550-58ef-a415-304bf5e56dbf
|
package/dist/{package-subgraph-check-C5S8yvBI.mjs.map → package-subgraph-check-DhCWO3YR.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-subgraph-check-C5S8yvBI.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;EAAE;EACpD,KAAK,aACH,OAAO,EACL,QAAQ,UAAU,WAAW,KAAK,WAAW;GAC3C;GACA,OAAO,OAAO,IAAI,KAAK,KAAA;EACzB,EAAE,EACJ;CACJ;AACF;;AAGA,SAAgB,sBACd,WACA,gBACuB;CACvB,MAAM,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subgraph-check-DhCWO3YR.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;EAAE;EACpD,KAAK,aACH,OAAO,EACL,QAAQ,UAAU,WAAW,KAAK,WAAW;GAC3C;GACA,OAAO,OAAO,IAAI,KAAK,KAAA;EACzB,EAAE,EACJ;CACJ;AACF;;AAGA,SAAgB,sBACd,WACA,gBACuB;CACvB,MAAM,gBAAuC,eAAe,KAAK,YAAY,EAC3E,eAAe,EAAE,OAAO,EAC1B,EAAE;CACF,MAAM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eof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="6b243612-2bd6-5c74-bfd1-feb7bb8cb59d")}catch(e){}}();
|
|
3
3
|
import { a as syncDirectory, o as syncTree, t as fromPGliteErrorInfo } from "./error-info-CCQcLAcW.mjs";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
|
-
import { childLogger } from "document-model";
|
|
6
5
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
6
|
+
import { childLogger } from "document-model";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { existsSync, promises } from "node:fs";
|
|
9
9
|
import { PGlite } from "@electric-sql/pglite";
|
|
@@ -698,5 +698,5 @@ const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();
|
|
|
698
698
|
//#endregion
|
|
699
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 };
|
|
700
700
|
|
|
701
|
-
//# sourceMappingURL=pglite-node-
|
|
702
|
-
//# debugId=
|
|
701
|
+
//# sourceMappingURL=pglite-node-BMux5A2Y.mjs.map
|
|
702
|
+
//# debugId=6b243612-2bd6-5c74-bfd1-feb7bb8cb59d
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pglite-node-BOFT_yUj.mjs","sources":["../src/pglite/snapshot-reader.ts","../src/pglite/convert-snapshot-dir.ts","../src/pglite/preflight.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","/** 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 (30 min); 0 waits for the quiet window only. */\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 { 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 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,kB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Aa,cAAc,IAAI,IAAI,UAAU,YAAY,GAAG,CAAC,CACpD,CAAC,CAAC,MAAM,cAAc,WAAW,SAAS,CAAC,KAAK;AAClE;AAEA,SAAS,yBAAwC;CAC/C,MAAM,YAAY,cAChB,IAAI,IAAI,0BAA0B,YAAY,GAAG,CACnD;CACA,IAAI,CAAC,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":"f6b44ee1-02f4-57d0-aeea-150475095c5a"}
|
|
1
|
+
{"version":3,"file":"pglite-node-BMux5A2Y.mjs","sources":["../src/pglite/snapshot-reader.ts","../src/pglite/convert-snapshot-dir.ts","../src/pglite/preflight.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","/** 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 (30 min); 0 waits for the quiet window only. */\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 { 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 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;CAG1D,MAAM,UAAU,OAAO,aAAa,CAAC;CACrC,IAAI,YAAY,gBACd,MAAM,IAAI,MAAM,8CAA8C,SAAS;CAEzE,MAAM,QAAQ,OAAO,aAAa,CAAC;CAEnC,MAAM,UAAU,IAAI,YAAY;CAChC,IAAI;CACJ,IAAI;CACJ,IAAI,UAAU;CAEd,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,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ph-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-
|
|
7
|
+
const { checkPackageSubgraphs } = await import("../../package-subgraph-check-DhCWO3YR.mjs");
|
|
8
8
|
return checkPackageSubgraphs(subgraphs, documentModels);
|
|
9
9
|
}
|
|
10
10
|
//#endregion
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
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-
|
|
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";
|
|
4
4
|
import { childLogger } from "document-model";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as syncDirectory, c as DEFAULT_VACUUM_FULL_ABOVE_BYTES, d as PGLITE_UTC_PARSERS, i as resolvePgliteFsync, l as DEFAULT_VACUUM_FULL_QUIET_MS, n as toPGliteErrorInfo, o as syncTree, r as createDurableNodeFs, s as DEFAULT_MAINTENANCE_INTERVAL_MS, t as fromPGliteErrorInfo, u as PgliteMaintenance } from "../../error-info-CCQcLAcW.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-
|
|
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-BMux5A2Y.mjs";
|
|
3
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_QUIET_MS, PGLITE_UTC_PARSERS, PGliteWorkerClosedError, PGliteWorkerError, PGliteWorkerExitedError, PGliteWorkerInitError, PgliteMaintenance, SNAPSHOT_FILE_NAME, ThreadedPGlite, convertSnapshotDir, createDurableNodeFs, extractSnapshot, fromPGliteErrorInfo, openCurrentPgliteForVerify, pgliteWorkerEntryPath, preparePgliteDataDir, recoverConversion, removeStalePgliteFiles, resolvePgliteFsync, 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]="
|
|
5
|
-
//# debugId=
|
|
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]="92a33329-187b-549c-b88b-bf14448a439e")}catch(e){}}();
|
|
5
|
+
//# debugId=92a33329-187b-549c-b88b-bf14448a439e
|