@powerhousedao/reactor-attachments 6.2.3 → 6.3.0-dev.2

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.
@@ -0,0 +1,255 @@
1
+ import { a as parseRef } from "./switchboard-attachment-transport-BH3ZAmxE.js";
2
+ import { documentModelScalars } from "document-model/scalars";
3
+ import { constantCase, pascalCase } from "change-case";
4
+ import { Kind, buildASTSchema, getNamedType, isInputObjectType, isListType, isNonNullType, parse, print } from "graphql";
5
+ //#region src/reference-index/attachment-schema-compiler.ts
6
+ const ATTACHMENT_REF_TYPE = "AttachmentRef";
7
+ const MODEL_SCALAR_SCHEMAS = documentModelScalars.map(({ name }) => `scalar ${name}`);
8
+ function describeContext(context) {
9
+ return `document type "${context.documentType}", version ${context.version}, action "${context.actionType}"`;
10
+ }
11
+ function compilationError(context, reason) {
12
+ return /* @__PURE__ */ new Error(`Attachment schema compilation failed for ${describeContext(context)}: ${reason}`);
13
+ }
14
+ function extractionError(context, path, reason) {
15
+ return /* @__PURE__ */ new Error(`Attachment extraction failed for ${describeContext(context)} at ${path}: ${reason}`);
16
+ }
17
+ function applicableSpecification(module, context) {
18
+ const matches = module.documentModel.global.specifications.filter((specification) => specification.version === context.version);
19
+ if (matches.length !== 1) throw compilationError(context, matches.length === 0 ? "the module has no matching specification" : "the module has multiple matching specifications");
20
+ return matches[0];
21
+ }
22
+ function parseOperations(specification, context) {
23
+ return specification.modules.flatMap((moduleSpecification) => moduleSpecification.operations.map((operation) => {
24
+ if (operation.schema === null) return {
25
+ document: null,
26
+ operation
27
+ };
28
+ try {
29
+ return {
30
+ document: parse(operation.schema),
31
+ operation
32
+ };
33
+ } catch {
34
+ throw compilationError(context, "an operation has invalid GraphQL SDL");
35
+ }
36
+ }));
37
+ }
38
+ function selectOperation(operations, context) {
39
+ const matches = operations.filter(({ operation }) => operation.name !== null && constantCase(operation.name) === context.actionType);
40
+ if (matches.length > 1) throw compilationError(context, "multiple operations map to the action");
41
+ if (matches.length === 0) return null;
42
+ return matches[0];
43
+ }
44
+ function buildEffectiveSchema(specification, context) {
45
+ const stateSchemas = Object.values(specification.state).map((state) => state.schema);
46
+ const operationSchemas = specification.modules.flatMap((moduleSpecification) => moduleSpecification.operations.flatMap((operation) => operation.schema === null ? [] : [operation.schema]));
47
+ try {
48
+ const document = parse([
49
+ ...MODEL_SCALAR_SCHEMAS,
50
+ ...stateSchemas,
51
+ ...operationSchemas
52
+ ].filter(Boolean).join("\n\n"));
53
+ return buildASTSchema(dedupeTypeDefinitions(document));
54
+ } catch {
55
+ throw compilationError(context, "the effective GraphQL schema is invalid");
56
+ }
57
+ }
58
+ function dedupeTypeDefinitions(document) {
59
+ const seen = /* @__PURE__ */ new Map();
60
+ const definitions = document.definitions.filter((definition) => {
61
+ if (!("name" in definition) || definition.name?.value === void 0 || definition.kind === Kind.SCALAR_TYPE_DEFINITION) return true;
62
+ const name = definition.name.value;
63
+ const printed = print(definition);
64
+ const existing = seen.get(name);
65
+ if (existing === void 0) {
66
+ seen.set(name, printed);
67
+ return true;
68
+ }
69
+ return existing !== printed;
70
+ });
71
+ return {
72
+ ...document,
73
+ definitions
74
+ };
75
+ }
76
+ function attachmentReachableTypes(definitions) {
77
+ const reachable = /* @__PURE__ */ new Set();
78
+ let changed = true;
79
+ while (changed) {
80
+ changed = false;
81
+ for (const [name, definition] of definitions) {
82
+ if (reachable.has(name)) continue;
83
+ if (Object.values(definition.getFields()).some((field) => {
84
+ const typeName = getNamedType(field.type).name;
85
+ return typeName === ATTACHMENT_REF_TYPE || definitions.has(typeName) && reachable.has(typeName);
86
+ })) {
87
+ reachable.add(name);
88
+ changed = true;
89
+ }
90
+ }
91
+ }
92
+ return reachable;
93
+ }
94
+ function compileValuePlan(type, objectPlans) {
95
+ if (isNonNullType(type)) return {
96
+ ...compileValuePlan(type.ofType, objectPlans),
97
+ required: true
98
+ };
99
+ if (isListType(type)) return {
100
+ item: compileValuePlan(type.ofType, objectPlans),
101
+ kind: "list",
102
+ required: false
103
+ };
104
+ const typeName = type.name;
105
+ if (typeName === ATTACHMENT_REF_TYPE) return {
106
+ kind: "attachment",
107
+ required: false
108
+ };
109
+ const body = objectPlans.get(typeName);
110
+ if (!body) throw new Error(`Internal attachment schema plan error for ${typeName}`);
111
+ return {
112
+ body,
113
+ kind: "object",
114
+ required: false
115
+ };
116
+ }
117
+ function compileRootPlan(rootName, definitions) {
118
+ const reachable = attachmentReachableTypes(definitions);
119
+ if (!reachable.has(rootName)) return null;
120
+ const objectPlans = /* @__PURE__ */ new Map();
121
+ for (const name of reachable) objectPlans.set(name, { fields: [] });
122
+ for (const name of reachable) {
123
+ const definition = definitions.get(name);
124
+ const body = objectPlans.get(name);
125
+ if (!definition || !body) continue;
126
+ for (const field of Object.values(definition.getFields())) {
127
+ const typeName = getNamedType(field.type).name;
128
+ if (typeName !== ATTACHMENT_REF_TYPE && !reachable.has(typeName)) continue;
129
+ body.fields.push({
130
+ hasDefault: field.defaultValue !== void 0,
131
+ name: field.name,
132
+ value: compileValuePlan(field.type, objectPlans)
133
+ });
134
+ }
135
+ }
136
+ return objectPlans.get(rootName) ?? null;
137
+ }
138
+ function readOwnField(value, fieldName, context, path) {
139
+ try {
140
+ if (!Object.prototype.hasOwnProperty.call(value, fieldName)) return {
141
+ present: false,
142
+ value: void 0
143
+ };
144
+ return {
145
+ present: true,
146
+ value: value[fieldName]
147
+ };
148
+ } catch {
149
+ throw extractionError(context, path, "the declared field cannot be read");
150
+ }
151
+ }
152
+ function extractValue(plan, value, path, context, refs, seenRefs, activeObjects) {
153
+ if (value === null || value === void 0) {
154
+ if (plan.required) throw extractionError(context, path, "a required value is missing or null");
155
+ return;
156
+ }
157
+ if (plan.kind === "attachment") {
158
+ if (typeof value !== "string") throw extractionError(context, path, "expected an AttachmentRef string");
159
+ try {
160
+ parseRef(value);
161
+ } catch {
162
+ throw extractionError(context, path, "the AttachmentRef is malformed");
163
+ }
164
+ if (!seenRefs.has(value)) {
165
+ seenRefs.add(value);
166
+ refs.push(value);
167
+ }
168
+ return;
169
+ }
170
+ if (plan.kind === "list") {
171
+ if (!Array.isArray(value)) throw extractionError(context, path, "expected a list");
172
+ for (let index = 0; index < value.length; index += 1) extractValue(plan.item, value[index], `${path}[${index}]`, context, refs, seenRefs, activeObjects);
173
+ return;
174
+ }
175
+ if (typeof value !== "object" || Array.isArray(value)) throw extractionError(context, path, "expected an input object");
176
+ if (activeObjects.has(value)) throw extractionError(context, path, "the input value contains a cycle");
177
+ activeObjects.add(value);
178
+ try {
179
+ const record = value;
180
+ for (const field of plan.body.fields) {
181
+ const fieldPath = `${path}.${field.name}`;
182
+ const result = readOwnField(record, field.name, context, fieldPath);
183
+ if ((!result.present || result.value === void 0) && field.hasDefault) continue;
184
+ extractValue(field.value, result.value, fieldPath, context, refs, seenRefs, activeObjects);
185
+ }
186
+ } finally {
187
+ activeObjects.delete(value);
188
+ }
189
+ }
190
+ var SchemaCompiledAttachmentExtractor = class {
191
+ context;
192
+ rootPlan;
193
+ constructor(context, rootPlan) {
194
+ this.context = context;
195
+ this.rootPlan = rootPlan;
196
+ }
197
+ extract(action) {
198
+ if (action.type !== this.context.actionType) throw extractionError(this.context, "input", "the action type does not match the compiled schema");
199
+ if (!this.rootPlan) return [];
200
+ if (action.input === null || typeof action.input !== "object" || Array.isArray(action.input)) throw extractionError(this.context, "input", "expected an input object");
201
+ const refs = [];
202
+ const seenRefs = /* @__PURE__ */ new Set();
203
+ const activeObjects = /* @__PURE__ */ new WeakSet();
204
+ activeObjects.add(action.input);
205
+ try {
206
+ const input = action.input;
207
+ for (const field of this.rootPlan.fields) {
208
+ const path = `input.${field.name}`;
209
+ const result = readOwnField(input, field.name, this.context, path);
210
+ if ((!result.present || result.value === void 0) && field.hasDefault) continue;
211
+ extractValue(field.value, result.value, path, this.context, refs, seenRefs, activeObjects);
212
+ }
213
+ } finally {
214
+ activeObjects.delete(action.input);
215
+ }
216
+ return refs;
217
+ }
218
+ };
219
+ function compileExtractor(module, actionType) {
220
+ const context = {
221
+ actionType,
222
+ documentType: module.documentModel.global.id,
223
+ version: module.version ?? 1
224
+ };
225
+ const specification = applicableSpecification(module, context);
226
+ const selected = selectOperation(parseOperations(specification, context), context);
227
+ if (selected === null || selected.operation.schema === null) return new SchemaCompiledAttachmentExtractor(context, null);
228
+ const effectiveSchema = buildEffectiveSchema(specification, context);
229
+ const operationName = selected.operation.name;
230
+ if (operationName === null) throw compilationError(context, "the operation has no name");
231
+ const rootName = `${pascalCase(operationName)}Input`;
232
+ const definitions = /* @__PURE__ */ new Map();
233
+ for (const type of Object.values(effectiveSchema.getTypeMap())) if (isInputObjectType(type) && !type.name.startsWith("__")) definitions.set(type.name, type);
234
+ if (!(selected.document?.definitions.filter((definition) => (definition.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || definition.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) && definition.name.value === rootName))?.length || !definitions.has(rootName)) throw compilationError(context, `the operation does not declare its expected root input "${rootName}"`);
235
+ return new SchemaCompiledAttachmentExtractor(context, compileRootPlan(rootName, definitions));
236
+ }
237
+ var AttachmentSchemaCompiler = class {
238
+ cache = /* @__PURE__ */ new WeakMap();
239
+ forModuleAction(module, actionType) {
240
+ let moduleCache = this.cache.get(module);
241
+ if (!moduleCache) {
242
+ moduleCache = /* @__PURE__ */ new Map();
243
+ this.cache.set(module, moduleCache);
244
+ }
245
+ const cached = moduleCache.get(actionType);
246
+ if (cached) return cached;
247
+ const compiled = compileExtractor(module, actionType);
248
+ moduleCache.set(actionType, compiled);
249
+ return compiled;
250
+ }
251
+ };
252
+ //#endregion
253
+ export { AttachmentSchemaCompiler as t };
254
+
255
+ //# sourceMappingURL=attachment-schema-compiler-BytE6Hev.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachment-schema-compiler-BytE6Hev.js","names":[],"sources":["../src/reference-index/attachment-schema-compiler.ts"],"sourcesContent":["import type { AttachmentRef } from \"@powerhousedao/reactor\";\nimport { documentModelScalars } from \"document-model/scalars\";\nimport type {\n Action,\n DocumentModelModule,\n DocumentSpecification,\n OperationSpecification,\n} from \"@powerhousedao/shared/document-model\";\nimport { constantCase, pascalCase } from \"change-case\";\nimport {\n buildASTSchema,\n getNamedType,\n isInputObjectType,\n isListType,\n isNonNullType,\n Kind,\n parse,\n print,\n type DocumentNode,\n type GraphQLInputObjectType,\n type GraphQLInputType,\n type GraphQLSchema,\n} from \"graphql\";\nimport { parseRef } from \"../ref.js\";\nimport type {\n CompiledAttachmentExtractor,\n IAttachmentSchemaCompiler,\n} from \"./types.js\";\n\nconst ATTACHMENT_REF_TYPE = \"AttachmentRef\";\nconst MODEL_SCALAR_SCHEMAS = documentModelScalars.map(\n ({ name }) => `scalar ${name}`,\n);\n\ntype CompilerContext = {\n actionType: string;\n documentType: string;\n version: number;\n};\n\ntype ParsedOperation = {\n document: DocumentNode | null;\n operation: OperationSpecification;\n};\n\ntype ObjectPlan = {\n fields: FieldPlan[];\n};\n\ntype FieldPlan = {\n hasDefault: boolean;\n name: string;\n value: ValuePlan;\n};\n\ntype ReadFieldResult =\n | { present: false; value: undefined }\n | { present: true; value: unknown };\n\ntype ValuePlan =\n | {\n kind: \"attachment\";\n required: boolean;\n }\n | {\n item: ValuePlan;\n kind: \"list\";\n required: boolean;\n }\n | {\n body: ObjectPlan;\n kind: \"object\";\n required: boolean;\n };\n\nfunction describeContext(context: CompilerContext): string {\n return `document type \"${context.documentType}\", version ${context.version}, action \"${context.actionType}\"`;\n}\n\nfunction compilationError(context: CompilerContext, reason: string): Error {\n return new Error(\n `Attachment schema compilation failed for ${describeContext(context)}: ${reason}`,\n );\n}\n\nfunction extractionError(\n context: CompilerContext,\n path: string,\n reason: string,\n): Error {\n return new Error(\n `Attachment extraction failed for ${describeContext(context)} at ${path}: ${reason}`,\n );\n}\n\nfunction applicableSpecification(\n module: DocumentModelModule,\n context: CompilerContext,\n): DocumentSpecification {\n const matches = module.documentModel.global.specifications.filter(\n (specification) => specification.version === context.version,\n );\n if (matches.length !== 1) {\n throw compilationError(\n context,\n matches.length === 0\n ? \"the module has no matching specification\"\n : \"the module has multiple matching specifications\",\n );\n }\n return matches[0];\n}\n\nfunction parseOperations(\n specification: DocumentSpecification,\n context: CompilerContext,\n): ParsedOperation[] {\n return specification.modules.flatMap((moduleSpecification) =>\n moduleSpecification.operations.map((operation) => {\n if (operation.schema === null) return { document: null, operation };\n try {\n return { document: parse(operation.schema), operation };\n } catch {\n throw compilationError(context, \"an operation has invalid GraphQL SDL\");\n }\n }),\n );\n}\n\nfunction selectOperation(\n operations: ParsedOperation[],\n context: CompilerContext,\n): ParsedOperation | null {\n const matches = operations.filter(\n ({ operation }) =>\n operation.name !== null &&\n constantCase(operation.name) === context.actionType,\n );\n if (matches.length > 1) {\n throw compilationError(context, \"multiple operations map to the action\");\n }\n // Base/system actions (document creation, renames, undo) are not part of a\n // model's specification, so they cannot declare AttachmentRef fields.\n // They compile to the no-reference fast path instead of failing the stream.\n if (matches.length === 0) return null;\n return matches[0];\n}\n\nfunction buildEffectiveSchema(\n specification: DocumentSpecification,\n context: CompilerContext,\n): GraphQLSchema {\n const stateSchemas = Object.values(specification.state).map(\n (state) => state.schema,\n );\n const operationSchemas = specification.modules.flatMap(\n (moduleSpecification) =>\n moduleSpecification.operations.flatMap((operation) =>\n operation.schema === null ? [] : [operation.schema],\n ),\n );\n\n try {\n const document = parse(\n [...MODEL_SCALAR_SCHEMAS, ...stateSchemas, ...operationSchemas]\n .filter(Boolean)\n .join(\"\\n\\n\"),\n );\n return buildASTSchema(dedupeTypeDefinitions(document));\n } catch {\n throw compilationError(context, \"the effective GraphQL schema is invalid\");\n }\n}\n\n// Collapse identical repeats of a type (state schema vs operation schemas).\n// Conflicting or scalar duplicates stay in so the build still rejects them.\nfunction dedupeTypeDefinitions(document: DocumentNode): DocumentNode {\n const seen = new Map<string, string>();\n const definitions = document.definitions.filter((definition) => {\n if (\n !(\"name\" in definition) ||\n definition.name?.value === undefined ||\n definition.kind === Kind.SCALAR_TYPE_DEFINITION\n ) {\n return true;\n }\n const name = definition.name.value;\n const printed = print(definition);\n const existing = seen.get(name);\n if (existing === undefined) {\n seen.set(name, printed);\n return true;\n }\n return existing !== printed;\n });\n return { ...document, definitions };\n}\n\nfunction attachmentReachableTypes(\n definitions: Map<string, GraphQLInputObjectType>,\n): Set<string> {\n const reachable = new Set<string>();\n let changed = true;\n\n while (changed) {\n changed = false;\n for (const [name, definition] of definitions) {\n if (reachable.has(name)) continue;\n const reachesAttachment = Object.values(definition.getFields()).some(\n (field) => {\n const typeName = getNamedType(field.type).name;\n return (\n typeName === ATTACHMENT_REF_TYPE ||\n (definitions.has(typeName) && reachable.has(typeName))\n );\n },\n );\n if (reachesAttachment) {\n reachable.add(name);\n changed = true;\n }\n }\n }\n\n return reachable;\n}\n\nfunction compileValuePlan(\n type: GraphQLInputType,\n objectPlans: Map<string, ObjectPlan>,\n): ValuePlan {\n if (isNonNullType(type)) {\n return { ...compileValuePlan(type.ofType, objectPlans), required: true };\n }\n if (isListType(type)) {\n return {\n item: compileValuePlan(type.ofType, objectPlans),\n kind: \"list\",\n required: false,\n };\n }\n\n const typeName = type.name;\n if (typeName === ATTACHMENT_REF_TYPE) {\n return { kind: \"attachment\", required: false };\n }\n const body = objectPlans.get(typeName);\n if (!body) {\n throw new Error(`Internal attachment schema plan error for ${typeName}`);\n }\n return { body, kind: \"object\", required: false };\n}\n\nfunction compileRootPlan(\n rootName: string,\n definitions: Map<string, GraphQLInputObjectType>,\n): ObjectPlan | null {\n const reachable = attachmentReachableTypes(definitions);\n if (!reachable.has(rootName)) return null;\n\n const objectPlans = new Map<string, ObjectPlan>();\n for (const name of reachable) objectPlans.set(name, { fields: [] });\n\n for (const name of reachable) {\n const definition = definitions.get(name);\n const body = objectPlans.get(name);\n if (!definition || !body) continue;\n for (const field of Object.values(definition.getFields())) {\n const typeName = getNamedType(field.type).name;\n if (typeName !== ATTACHMENT_REF_TYPE && !reachable.has(typeName)) {\n continue;\n }\n body.fields.push({\n hasDefault: field.defaultValue !== undefined,\n name: field.name,\n value: compileValuePlan(field.type, objectPlans),\n });\n }\n }\n\n return objectPlans.get(rootName) ?? null;\n}\n\nfunction readOwnField(\n value: Record<string, unknown>,\n fieldName: string,\n context: CompilerContext,\n path: string,\n): ReadFieldResult {\n try {\n if (!Object.prototype.hasOwnProperty.call(value, fieldName)) {\n return { present: false, value: undefined };\n }\n return { present: true, value: value[fieldName] };\n } catch {\n throw extractionError(context, path, \"the declared field cannot be read\");\n }\n}\n\nfunction extractValue(\n plan: ValuePlan,\n value: unknown,\n path: string,\n context: CompilerContext,\n refs: AttachmentRef[],\n seenRefs: Set<string>,\n activeObjects: WeakSet<object>,\n): void {\n if (value === null || value === undefined) {\n if (plan.required) {\n throw extractionError(\n context,\n path,\n \"a required value is missing or null\",\n );\n }\n return;\n }\n\n if (plan.kind === \"attachment\") {\n if (typeof value !== \"string\") {\n throw extractionError(context, path, \"expected an AttachmentRef string\");\n }\n try {\n parseRef(value as AttachmentRef);\n } catch {\n throw extractionError(context, path, \"the AttachmentRef is malformed\");\n }\n if (!seenRefs.has(value)) {\n seenRefs.add(value);\n refs.push(value as AttachmentRef);\n }\n return;\n }\n\n if (plan.kind === \"list\") {\n if (!Array.isArray(value)) {\n throw extractionError(context, path, \"expected a list\");\n }\n for (let index = 0; index < value.length; index += 1) {\n extractValue(\n plan.item,\n value[index],\n `${path}[${index}]`,\n context,\n refs,\n seenRefs,\n activeObjects,\n );\n }\n return;\n }\n\n if (typeof value !== \"object\" || Array.isArray(value)) {\n throw extractionError(context, path, \"expected an input object\");\n }\n if (activeObjects.has(value)) {\n throw extractionError(context, path, \"the input value contains a cycle\");\n }\n\n activeObjects.add(value);\n try {\n const record = value as Record<string, unknown>;\n for (const field of plan.body.fields) {\n const fieldPath = `${path}.${field.name}`;\n const result = readOwnField(record, field.name, context, fieldPath);\n if ((!result.present || result.value === undefined) && field.hasDefault) {\n continue;\n }\n extractValue(\n field.value,\n result.value,\n fieldPath,\n context,\n refs,\n seenRefs,\n activeObjects,\n );\n }\n } finally {\n activeObjects.delete(value);\n }\n}\n\nclass SchemaCompiledAttachmentExtractor implements CompiledAttachmentExtractor {\n constructor(\n private readonly context: CompilerContext,\n private readonly rootPlan: ObjectPlan | null,\n ) {}\n\n extract(action: Action): AttachmentRef[] {\n if (action.type !== this.context.actionType) {\n throw extractionError(\n this.context,\n \"input\",\n \"the action type does not match the compiled schema\",\n );\n }\n if (!this.rootPlan) return [];\n if (\n action.input === null ||\n typeof action.input !== \"object\" ||\n Array.isArray(action.input)\n ) {\n throw extractionError(this.context, \"input\", \"expected an input object\");\n }\n\n const refs: AttachmentRef[] = [];\n const seenRefs = new Set<string>();\n const activeObjects = new WeakSet<object>();\n activeObjects.add(action.input);\n try {\n const input = action.input as Record<string, unknown>;\n for (const field of this.rootPlan.fields) {\n const path = `input.${field.name}`;\n const result = readOwnField(input, field.name, this.context, path);\n if (\n (!result.present || result.value === undefined) &&\n field.hasDefault\n ) {\n continue;\n }\n extractValue(\n field.value,\n result.value,\n path,\n this.context,\n refs,\n seenRefs,\n activeObjects,\n );\n }\n } finally {\n activeObjects.delete(action.input);\n }\n return refs;\n }\n}\n\nfunction compileExtractor(\n module: DocumentModelModule,\n actionType: string,\n): CompiledAttachmentExtractor {\n const context: CompilerContext = {\n actionType,\n documentType: module.documentModel.global.id,\n version: module.version ?? 1,\n };\n const specification = applicableSpecification(module, context);\n const operations = parseOperations(specification, context);\n const selected = selectOperation(operations, context);\n if (selected === null || selected.operation.schema === null) {\n return new SchemaCompiledAttachmentExtractor(context, null);\n }\n const effectiveSchema = buildEffectiveSchema(specification, context);\n\n const operationName = selected.operation.name;\n if (operationName === null) {\n throw compilationError(context, \"the operation has no name\");\n }\n const rootName = `${pascalCase(operationName)}Input`;\n const definitions = new Map<string, GraphQLInputObjectType>();\n for (const type of Object.values(effectiveSchema.getTypeMap())) {\n if (isInputObjectType(type) && !type.name.startsWith(\"__\")) {\n definitions.set(type.name, type);\n }\n }\n const rootDefinitions = selected.document?.definitions.filter(\n (definition) =>\n (definition.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ||\n definition.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) &&\n definition.name.value === rootName,\n );\n if (!rootDefinitions?.length || !definitions.has(rootName)) {\n throw compilationError(\n context,\n `the operation does not declare its expected root input \"${rootName}\"`,\n );\n }\n\n return new SchemaCompiledAttachmentExtractor(\n context,\n compileRootPlan(rootName, definitions),\n );\n}\n\nexport class AttachmentSchemaCompiler implements IAttachmentSchemaCompiler {\n private readonly cache = new WeakMap<\n DocumentModelModule,\n Map<string, CompiledAttachmentExtractor>\n >();\n\n forModuleAction(\n module: DocumentModelModule,\n actionType: string,\n ): CompiledAttachmentExtractor {\n let moduleCache = this.cache.get(module);\n if (!moduleCache) {\n moduleCache = new Map();\n this.cache.set(module, moduleCache);\n }\n\n const cached = moduleCache.get(actionType);\n if (cached) return cached;\n\n const compiled = compileExtractor(module, actionType);\n moduleCache.set(actionType, compiled);\n return compiled;\n }\n}\n"],"mappings":";;;;;AA6BA,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB,qBAAqB,KAC/C,EAAE,WAAW,UAAU,MAC1B;AA2CA,SAAS,gBAAgB,SAAkC;CACzD,OAAO,kBAAkB,QAAQ,aAAa,aAAa,QAAQ,QAAQ,YAAY,QAAQ,WAAW;AAC5G;AAEA,SAAS,iBAAiB,SAA0B,QAAuB;CACzE,uBAAO,IAAI,MACT,4CAA4C,gBAAgB,OAAO,EAAE,IAAI,QAC3E;AACF;AAEA,SAAS,gBACP,SACA,MACA,QACO;CACP,uBAAO,IAAI,MACT,oCAAoC,gBAAgB,OAAO,EAAE,MAAM,KAAK,IAAI,QAC9E;AACF;AAEA,SAAS,wBACP,QACA,SACuB;CACvB,MAAM,UAAU,OAAO,cAAc,OAAO,eAAe,QACxD,kBAAkB,cAAc,YAAY,QAAQ,OACvD;CACA,IAAI,QAAQ,WAAW,GACrB,MAAM,iBACJ,SACA,QAAQ,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nC,IAAI,EANoB,SAAS,UAAU,YAAY,QACpD,gBACE,WAAW,SAAS,KAAK,gCACxB,WAAW,SAAS,KAAK,gCAC3B,WAAW,KAAK,UAAU,QAC9B,EAAA,EACsB,UAAU,CAAC,YAAY,IAAI,QAAQ,GACvD,MAAM,iBACJ,SACA,2DAA2D,SAAS,EACtE;CAGF,OAAO,IAAI,kCACT,SACA,gBAAgB,UAAU,WAAW,CACvC;AACF;AAEA,IAAa,2BAAb,MAA2E;CACzE,wBAAyB,IAAI,QAG3B;CAEF,gBACE,QACA,YAC6B;EAC7B,IAAI,cAAc,KAAK,MAAM,IAAI,MAAM;EACvC,IAAI,CAAC,aAAa;GAChB,8BAAc,IAAI,IAAI;GACtB,KAAK,MAAM,IAAI,QAAQ,WAAW;EACpC;EAEA,MAAM,SAAS,YAAY,IAAI,UAAU;EACzC,IAAI,QAAQ,OAAO;EAEnB,MAAM,WAAW,iBAAiB,QAAQ,UAAU;EACpD,YAAY,IAAI,YAAY,QAAQ;EACpC,OAAO;CACT;AACF"}
package/dist/client.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { $ as AttachmentNotFound, A as IReservationStore, B as AttachmentStatOptions, C as IAttachmentReader, D as IAttachmentTransportFactory, E as IAttachmentTransport, F as AttachmentDownloadTargetOptions, G as AttachmentUploadTarget, H as AttachmentTargetHeaders, I as AttachmentHeader, J as ReserveAttachmentOptions, K as HashFirstReserveAttachmentOptions, L as AttachmentMetadata, N as AttachmentDownloadOptions, O as IAttachmentUpload, P as AttachmentDownloadTarget, Q as AttachmentAlreadyExists, R as AttachmentResponse, T as IAttachmentStore, U as AttachmentTransportConfig, V as AttachmentStatus, W as AttachmentUploadResult, X as TransportResponse, Y as TransportFetchResult, Z as UploadFirstReserveAttachmentOptions, _ as createRef, a as RemoteAttachmentUpload, at as ReservationNotFound, b as parseAttachmentDownloadTarget, c as XhrUploadTransportOptions, d as AttachmentUploadResponse, et as AttachmentPending, f as AttachmentUploadTransport, g as ParsedRef, h as SwitchboardTransportConfig, i as RemoteAttachmentUploadFactory, it as InvalidAttachmentRef, k as IAttachmentUploadFactory, l as createXhrUploadTransport, m as SwitchboardAttachmentTransport, n as createRemoteAttachmentService, nt as AttachmentTransferStage, o as RemoteReservationStore, ot as SizeMismatch, p as createFetchUploadTransport, q as Reservation, r as RemoteAttachmentStore, rt as HashMismatch, s as SwitchboardClientConfig, st as UploadTooLarge, t as NullAttachmentTransport, tt as AttachmentTransferError, u as AttachmentUploadRequest, v as parseRef, w as IAttachmentService, x as parseAttachmentUploadTarget, y as AttachmentService, z as AttachmentSendOptions } from "./null-attachment-transport-BkM6rq4R.js";
1
+ import { A as HashMismatch, C as parseAttachmentUploadTarget, D as AttachmentPending, E as AttachmentNotFound, F as UploadTooLarge, M as InvalidAttachmentRef, N as ReservationNotFound, O as AttachmentTransferError, P as SizeMismatch, S as parseAttachmentDownloadTarget, _ as SwitchboardTransportConfig, a as RemoteAttachmentStore, b as parseRef, c as RemoteReservationStore, d as createXhrUploadTransport, f as AttachmentUploadRequest, g as SwitchboardAttachmentTransport, h as createFetchUploadTransport, i as createRemoteAttachmentService, k as AttachmentTransferStage, l as SwitchboardClientConfig, m as AttachmentUploadTransport, n as RoutingAttachmentService, o as RemoteAttachmentUploadFactory, p as AttachmentUploadResponse, r as NullAttachmentTransport, s as RemoteAttachmentUpload, t as AttachmentRouteResolver, u as XhrUploadTransportOptions, v as ParsedRef, w as AttachmentAlreadyExists, x as AttachmentService, y as createRef } from "./routing-attachment-service-Dri6e2Vz.js";
2
+ import { A as UploadFirstReserveAttachmentOptions, C as AttachmentUploadResult, D as ReserveAttachmentOptions, E as Reservation, O as TransportFetchResult, S as AttachmentTransportConfig, T as HashFirstReserveAttachmentOptions, _ as AttachmentResponse, a as IAttachmentTransport, b as AttachmentStatus, c as IAttachmentUploadFactory, f as AttachmentDownloadOptions, g as AttachmentMetadata, h as AttachmentHeader, i as IAttachmentStore, k as TransportResponse, l as IReservationStore, m as AttachmentDownloadTargetOptions, n as IAttachmentReader, o as IAttachmentTransportFactory, p as AttachmentDownloadTarget, r as IAttachmentService, s as IAttachmentUpload, v as AttachmentSendOptions, w as AttachmentUploadTarget, x as AttachmentTargetHeaders, y as AttachmentStatOptions } from "./interfaces-cFMtcMqR.js";
2
3
  import { AttachmentHash, AttachmentRef } from "@powerhousedao/reactor";
3
4
  //#region src/concurrency.d.ts
4
5
  /**
@@ -161,18 +162,30 @@ type ByteProgressHooks = {
161
162
  export declare function withByteProgress(source: ReadableStream<Uint8Array>, hooks: ByteProgressHooks): ReadableStream<Uint8Array>;
162
163
  //#endregion
163
164
  //#region src/client.d.ts
165
+ export type PreprocessOptions = {
166
+ fileName?: string;
167
+ mimeType?: string;
168
+ /** The document the attachment is for; see `ReserveAttachmentOptions`. */
169
+ documentId?: string;
170
+ };
164
171
  export type PreprocessResult = {
165
172
  ref: AttachmentRef;
166
173
  hash: AttachmentHash;
167
174
  sizeBytes: number;
168
175
  options: HashFirstReserveAttachmentOptions;
176
+ /** @deprecated Read `blob`; this is a stream of its bytes. */
169
177
  data: ReadableStream<Uint8Array>;
178
+ /** @deprecated Read `blob`; each call is a new stream of its bytes. */
170
179
  stream: () => ReadableStream<Uint8Array>;
180
+ /** The file itself; uploads send it as-is, so a browser streams it from disk. */
181
+ blob: Blob;
171
182
  };
172
183
  export type AttachmentUploadInput = {
173
184
  file: Blob;
174
185
  fileName?: string;
175
186
  mimeType?: string;
187
+ /** The document the attachment is for; see `ReserveAttachmentOptions`. */
188
+ documentId?: string;
176
189
  /** Per-item cancellation, checked between stages. */
177
190
  signal?: AbortSignal;
178
191
  };
@@ -266,10 +279,7 @@ export type AttachmentBatchCounts = {
266
279
  };
267
280
  export declare const DEFAULT_ATTACHMENT_BATCH_CONCURRENCY = 4;
268
281
  export interface IAttachmentClient {
269
- preprocess(file: Blob, opts?: {
270
- fileName?: string;
271
- mimeType?: string;
272
- }): Promise<PreprocessResult>;
282
+ preprocess(file: Blob, opts?: PreprocessOptions): Promise<PreprocessResult>;
273
283
  reserve(options: HashFirstReserveAttachmentOptions, send: (handle: IAttachmentUpload) => Promise<AttachmentUploadResult>): Promise<AttachmentUploadResult>;
274
284
  /**
275
285
  * Hash, reserve, and transfer one file; a confirmed dedup skips the transfer
@@ -319,6 +329,6 @@ export interface IAttachmentClient {
319
329
  }
320
330
  export declare function createAttachmentClient(service: IAttachmentService): IAttachmentClient;
321
331
  //#endregion
322
- export { AttachmentAlreadyExists, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, AttachmentNotFound, AttachmentPending, type AttachmentProgress, type AttachmentProgressListener, type AttachmentProgressOptions, type AttachmentResponse, type AttachmentSendOptions, AttachmentService, type AttachmentStage, type AttachmentStatOptions, type AttachmentStatus, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type BatchItemResult, type ByteProgressHooks, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentReader, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, type ProgressEmitterOptions, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, type RunWithConcurrencyOptions, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
332
+ export { AttachmentAlreadyExists, type AttachmentDownloadOptions, type AttachmentDownloadTarget, type AttachmentDownloadTargetOptions, type AttachmentHeader, type AttachmentMetadata, AttachmentNotFound, AttachmentPending, type AttachmentProgress, type AttachmentProgressListener, type AttachmentProgressOptions, type AttachmentResponse, type AttachmentRouteResolver, type AttachmentSendOptions, AttachmentService, type AttachmentStage, type AttachmentStatOptions, type AttachmentStatus, type AttachmentTargetHeaders, AttachmentTransferError, type AttachmentTransferStage, type AttachmentTransportConfig, type AttachmentUploadRequest, type AttachmentUploadResponse, type AttachmentUploadResult, type AttachmentUploadTarget, type AttachmentUploadTransport, type BatchItemResult, type ByteProgressHooks, type HashFirstReserveAttachmentOptions, HashMismatch, type IAttachmentReader, type IAttachmentService, type IAttachmentStore, type IAttachmentTransport, type IAttachmentTransportFactory, type IAttachmentUpload, type IAttachmentUploadFactory, type IReservationStore, InvalidAttachmentRef, NullAttachmentTransport, type ParsedRef, type ProgressEmitterOptions, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, type Reservation, ReservationNotFound, type ReserveAttachmentOptions, RoutingAttachmentService, type RunWithConcurrencyOptions, SizeMismatch, SwitchboardAttachmentTransport, type SwitchboardClientConfig, type SwitchboardTransportConfig, type TransportFetchResult, type TransportResponse, type UploadFirstReserveAttachmentOptions, UploadTooLarge, type XhrUploadTransportOptions, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef };
323
333
  export {};
324
334
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"mappings":";;;;;;;;KAKY,gBAAgB;EACtB;EAAe;EAAqB,OAAO;;EAC3C;EAAe;EAAoB;;KAE7B,0BAA0B;;EAEpC;;;;;;EAMA,SAAS;;;;;;;EAOT,aAAa,QAAQ,gBAAgB;;;;;;;wBAQjB,mBAAmB,GAAG,GAC1C,gBAAgB,KAChB,SAAS,MAA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,UAAU,4BACT,QAAQ;;;;;;;;;EASX,SACE,OAAO,yBACP,UAAU,4BACT,QAAQ;;;;;;EAMX,aACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;EAMX,eACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC;;;;;;EAMH,kBACE,OAAO,yBACP,UAAU,wBAAwB,4BACjC,QAAQ;;;;;;;;EAQX,aAAa,OAAO,2BAA2B,QAAQ;EACvD,WACE,iBAAiB,yBACjB,UAAU,yBACT,QAAQ,gBAAgB;EAC3B,aACE,iBAAiB,2BACjB,UAAU,yBACT,QAAQ,gBAAgB;;wBAgYb,uBACd,SAAS,qBACR"}
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../src/concurrency.ts","../src/progress.ts","../src/client.ts"],"mappings":";;;;;;;;;KAKY,gBAAgB;EACtB;EAAe;EAAqB,OAAO;;EAC3C;EAAe;EAAoB;;KAE7B,0BAA0B;;EAEpC;;;;;;EAMA,SAAS;;;;;;;EAOT,aAAa,QAAQ,gBAAgB;;;;;;;wBAQjB,mBAAmB,GAAG,GAC1C,gBAAgB,KAChB,SAAS,MAAM,GAAG,kBAAkB,QAAQ,IAC5C,SAAS,0BAA0B,KAClC,QAAQ,gBAAgB;;;;;;;;;;;KC3Bf;KASA;EACV,OAAO;;EAEP;;EAEA;;EAEA;;EAEA;;KAGU,8BAA8B,UAAU;KAExC;EACV,aAAa;;EAEb;;qBAGW;;;;;;wBAOG,iBAAiB,UAAU;KAS/B,yBAAyB;;EAEnC;;;;;;;;;;;;;;;;;qBAkBW;mBACM;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAU;;MAOlB;;;;;;EASJ,MAAM,OAAO,iBAAiB;IAAY;;;;;;EAkB1C,MAAM,gBAAgB;;;;;EAoBtB,OAAO;IAAa;IAAiB;IAAgB;;;EAerD;;EAKA;UAWQ;;KAME;;EAEV,WAAW;;EAEX;EACA,WAAW;;;;;;;;;;;;;;;;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as SizeMismatch, _ as AttachmentPending, a as RemoteAttachmentUpload, b as InvalidAttachmentRef, c as createFetchUploadTransport, d as createRef, f as parseRef, g as AttachmentNotFound, h as AttachmentAlreadyExists, i as RemoteAttachmentUploadFactory, l as SwitchboardAttachmentTransport, m as parseAttachmentUploadTarget, n as createRemoteAttachmentService, o as RemoteReservationStore, p as parseAttachmentDownloadTarget, r as RemoteAttachmentStore, s as createXhrUploadTransport, t as NullAttachmentTransport, u as AttachmentService, v as AttachmentTransferError, x as ReservationNotFound, y as HashMismatch } from "./null-attachment-transport-D53Rz9lE.js";
1
+ import { a as parseRef, c as AttachmentPending, f as InvalidAttachmentRef, h as UploadTooLarge, i as createRef, l as AttachmentTransferError, m as SizeMismatch, o as AttachmentAlreadyExists, p as ReservationNotFound, s as AttachmentNotFound, t as SwitchboardAttachmentTransport, u as HashMismatch } from "./switchboard-attachment-transport-BH3ZAmxE.js";
2
+ import { a as RemoteAttachmentUploadFactory, c as createXhrUploadTransport, f as AttachmentService, i as RemoteAttachmentStore, l as createFetchUploadTransport, m as parseAttachmentUploadTarget, n as NullAttachmentTransport, o as RemoteAttachmentUpload, p as parseAttachmentDownloadTarget, r as createRemoteAttachmentService, s as RemoteReservationStore, t as RoutingAttachmentService, u as blobStream } from "./routing-attachment-service-C88ryRgj.js";
3
+ import { n as sha256HexOfBlob } from "./hash-BobbR4r4.js";
2
4
  //#region src/concurrency.ts
3
5
  /**
4
6
  * Runs `worker` over `items` with a hard upper bound on simultaneous
@@ -254,12 +256,6 @@ function dedupedHeader(hash, options) {
254
256
  expiresAtUtc: null
255
257
  };
256
258
  }
257
- function streamFromBuffer(buf) {
258
- return new ReadableStream({ start(controller) {
259
- controller.enqueue(buf);
260
- controller.close();
261
- } });
262
- }
263
259
  /** Stamps an item's index onto its progress events. */
264
260
  function itemProgress(options, index) {
265
261
  if (!options?.onProgress && options?.throttleMs === void 0) return;
@@ -297,28 +293,30 @@ var AttachmentClientImpl = class {
297
293
  constructor(service) {
298
294
  this.service = service;
299
295
  }
300
- async preprocess(file, opts) {
301
- const buf = await file.arrayBuffer();
302
- const bytes = new Uint8Array(buf);
303
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
304
- const hash = Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
296
+ preprocess(file, opts) {
297
+ return this.hashFile(file, opts);
298
+ }
299
+ async hashFile(file, opts, signal) {
300
+ const hash = await sha256HexOfBlob(file, signal ? { signal } : void 0);
305
301
  const ref = createRef(hash);
306
302
  const sizeBytes = file.size;
307
303
  const options = {
308
304
  mimeType: opts?.mimeType ?? file.type,
309
305
  fileName: opts?.fileName ?? (file instanceof File ? file.name : "attachment"),
310
306
  clientHash: hash,
311
- sizeBytes
307
+ sizeBytes,
308
+ ...opts?.documentId !== void 0 ? { documentId: opts.documentId } : {}
312
309
  };
313
- const data = streamFromBuffer(bytes);
314
- const stream = () => streamFromBuffer(bytes);
310
+ const data = blobStream(file);
311
+ const stream = () => blobStream(file);
315
312
  return {
316
313
  ref,
317
314
  hash,
318
315
  sizeBytes,
319
316
  options,
320
317
  data,
321
- stream
318
+ stream,
319
+ blob: file
322
320
  };
323
321
  }
324
322
  /**
@@ -358,10 +356,11 @@ var AttachmentClientImpl = class {
358
356
  if ("preprocessed" in input) preprocessed = input.preprocessed;
359
357
  else {
360
358
  emitter.stage("hashing", { total: input.file.size });
361
- preprocessed = await this.preprocess(input.file, {
359
+ preprocessed = await this.hashFile(input.file, {
362
360
  ...input.fileName !== void 0 ? { fileName: input.fileName } : {},
363
- ...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {}
364
- });
361
+ ...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {},
362
+ ...input.documentId !== void 0 ? { documentId: input.documentId } : {}
363
+ }, signal);
365
364
  }
366
365
  const sizeBytes = preprocessed.sizeBytes;
367
366
  signal?.throwIfAborted();
@@ -377,7 +376,7 @@ var AttachmentClientImpl = class {
377
376
  ...emitter.active ? { onProgress: (loaded, total) => emitter.bytes(loaded, total ?? sizeBytes) } : {},
378
377
  ...signal ? { signal } : {}
379
378
  };
380
- const result = await outcome.handle.send(preprocessed.stream(), sendOptions);
379
+ const result = await outcome.handle.send(preprocessed.blob, sendOptions);
381
380
  emitter.finish();
382
381
  return result;
383
382
  } catch (err) {
@@ -507,6 +506,6 @@ function createAttachmentClient(service) {
507
506
  return new AttachmentClientImpl(service);
508
507
  }
509
508
  //#endregion
510
- export { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };
509
+ export { AttachmentAlreadyExists, AttachmentNotFound, AttachmentPending, AttachmentService, AttachmentTransferError, DEFAULT_ATTACHMENT_BATCH_CONCURRENCY, DEFAULT_PROGRESS_THROTTLE_MS, HashMismatch, InvalidAttachmentRef, NullAttachmentTransport, ProgressEmitter, RemoteAttachmentStore, RemoteAttachmentUpload, RemoteAttachmentUploadFactory, RemoteReservationStore, ReservationNotFound, RoutingAttachmentService, SizeMismatch, SwitchboardAttachmentTransport, UploadTooLarge, createAttachmentClient, createFetchUploadTransport, createRef, createRemoteAttachmentService, createXhrUploadTransport, parseAttachmentDownloadTarget, parseAttachmentUploadTarget, parseRef, progressFraction, runWithConcurrency, withByteProgress };
511
510
 
512
511
  //# sourceMappingURL=client.js.map