@brickkit/cli 0.2.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +114 -15
- package/dist/bin.js +39 -1
- package/dist/bin.js.map +1 -1
- package/dist/build.js +4 -0
- package/dist/build.js.map +1 -1
- package/dist/client-contract.js +168 -0
- package/dist/client-contract.js.map +1 -0
- package/dist/compiler2.js +2 -10
- package/dist/compiler2.js.map +1 -1
- package/dist/index.d.ts +10 -37
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -86
- package/dist/vite.d.ts +12 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +118 -0
- package/dist/vite.js.map +1 -0
- package/package.json +23 -5
- package/vite-client.d.ts +4 -0
- package/dist/index.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-contract.js","names":[],"sources":["../src/client-contract.ts"],"sourcesContent":["import type { Service } from \"@brickkit/core\";\nimport type { BrickClientAction } from \"@brickkit/core/client\";\nimport type { BrickApp } from \"./endpoints\";\n\n/** Generate browser metadata and transport types from the app's selected services. */\nexport function generateClientContract(app: BrickApp): string {\n const { services, prefix } = app.definition;\n const contract: Record<string, any> = Object.create(null);\n const types: Record<string, any> = Object.create(null);\n const resourceActions = new Set<unknown>();\n for (const service of services) {\n addResources(service, prefix, contract, types, resourceActions);\n }\n for (const service of services) {\n addServiceActions(service, prefix, contract, types, resourceActions);\n }\n return `// Generated by the Brick Vite plugin. Do not edit.\nimport type { BrickClientAction } from \"@brickkit/core/client\";\n\nexport type AppContract = ${namespaceType(types)};\n\nexport const contract: AppContract = JSON.parse(${JSON.stringify(JSON.stringify(contract))});\n`;\n}\n\nfunction addResources(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n) {\n for (const resource of service.listResources()) {\n if (Object.hasOwn(contract, resource.name))\n throw new Error(`Brick client: duplicate namespace '${resource.name}'`);\n const node: Record<string, any> = Object.create(null);\n const typeNode: Record<string, any> = Object.create(null);\n contract[resource.name] = node;\n types[resource.name] = typeNode;\n const enabled = new Set(service.listActions());\n for (const [operation, method, item] of [\n [\"list\", \"GET\", false],\n [\"create\", \"POST\", false],\n [\"get\", \"GET\", true],\n [\"update\", \"PATCH\", true],\n [\"delete\", \"DELETE\", true],\n ] as const) {\n const action = resource.actions[operation];\n resourceActions.add(action);\n if (!enabled.has(action)) continue;\n const itemPath = item ? `/:${resource.idField}` : \"\";\n const path = `${prefix}/${resource.name}${itemPath}`;\n node[operation] = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: { path, method },\n };\n const inputType = schemaType(action.config.input);\n // The runtime list result always includes these metadata fields.\n const outputSchema =\n operation === \"list\"\n ? {\n ...action.config.output,\n required: [\n ...new Set([\n ...(action.config.output?.required ?? []),\n \"items\",\n \"total\",\n \"limit\",\n \"offset\",\n \"pageCount\",\n \"hasMore\",\n \"nextCursor\",\n ]),\n ],\n }\n : action.config.output;\n typeNode[operation] = actionType(\n inputType,\n schemaType(outputSchema),\n action.config.errors,\n );\n }\n }\n}\n\nfunction addServiceActions(\n service: Service<any, any>,\n prefix: string,\n contract: Record<string, any>,\n types: Record<string, any>,\n resourceActions: Set<unknown>,\n) {\n const namespace: Record<string, any> =\n contract[service.name] ?? Object.create(null);\n const namespaceTypes: Record<string, any> =\n types[service.name] ?? Object.create(null);\n contract[service.name] = namespace;\n types[service.name] = namespaceTypes;\n for (const action of service.listActions()) {\n if (resourceActions.has(action)) continue;\n const { input, output, errors, path, method } = action.config;\n let inputType: string;\n let outputType: string;\n try {\n inputType = input ? schemaType(input) : \"unknown\";\n outputType = output ? schemaType(output) : \"unknown\";\n } catch (error) {\n throw new Error(\n `Brick client: cannot generate '${service.name}.${action.name}': ${(error as Error).message}`,\n );\n }\n const metadata: BrickClientAction = {\n kind: \"action\",\n name: action.name,\n serviceName: service.name,\n config: {\n path: path ?? `${prefix}/${service.name}/${action.name}`,\n method: method ?? \"POST\",\n },\n };\n insertAction(\n namespace,\n namespaceTypes,\n metadata,\n actionType(inputType, outputType, errors),\n );\n }\n}\n\nfunction insertAction(\n node: Record<string, any>,\n typeNode: Record<string, any>,\n metadata: BrickClientAction,\n type: string,\n) {\n const segments = metadata.name.split(\".\");\n for (const segment of segments.slice(0, -1)) {\n if (\n Object.hasOwn(typeNode, segment) &&\n typeof typeNode[segment] === \"string\"\n ) {\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n }\n node[segment] ??= Object.create(null);\n typeNode[segment] ??= Object.create(null);\n node = node[segment];\n typeNode = typeNode[segment];\n }\n const leaf = segments.at(-1)!;\n if (Object.hasOwn(node, leaf))\n throw new Error(\n `Brick client: action namespace collision at '${metadata.serviceName}.${metadata.name}'`,\n );\n node[leaf] = metadata;\n typeNode[leaf] = type;\n}\n\nfunction actionType(\n input: string,\n output: string,\n errors: Record<string, unknown> | undefined,\n): string {\n const codes = Object.keys(errors ?? {});\n const errorsType = codes.length\n ? `Record<${codes.map((code) => JSON.stringify(code)).join(\" | \")}, { message: string; status?: number }>`\n : \"{}\";\n return `BrickClientAction<${input}, ${output}, ${errorsType}>`;\n}\n\nfunction namespaceType(node: Record<string, any>): string {\n return `{\\n${Object.entries(node)\n .map(\n ([key, value]) =>\n ` ${JSON.stringify(key)}: ${typeof value === \"string\" ? value : namespaceType(value)};`,\n )\n .join(\"\\n\")}\\n}`;\n}\n\n// Emit transport types from schemas, rather than importing backend callbacks or databases.\nfunction schemaType(schema: any): string {\n if (schema === undefined) return \"unknown\";\n if (schema === true) return \"unknown\";\n if (schema === false || (schema.not && !Object.keys(schema.not).length))\n return \"never\";\n if (schema.$ref)\n throw new Error(`unresolved schema reference '${schema.$ref}'`);\n if (Object.hasOwn(schema, \"const\")) return JSON.stringify(schema.const);\n if (schema.enum)\n return (\n schema.enum.map((value: unknown) => JSON.stringify(value)).join(\" | \") ||\n \"never\"\n );\n if (schema.anyOf || schema.oneOf)\n return `(${(schema.anyOf ?? schema.oneOf).map(schemaType).join(\" | \")})`;\n if (schema.allOf) return `(${schema.allOf.map(schemaType).join(\" & \")})`;\n switch (schema.type) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"integer\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"null\":\n return \"null\";\n case \"undefined\":\n case \"void\":\n return \"undefined\";\n case \"array\":\n return arraySchemaType(schema);\n case \"object\":\n return objectSchemaType(schema);\n case undefined:\n return \"unknown\";\n default:\n throw new Error(`unsupported transport schema type '${schema.type}'`);\n }\n}\n\nfunction arraySchemaType(schema: any): string {\n if (Array.isArray(schema.items))\n return `[${schema.items.map(schemaType).join(\", \")}]`;\n const itemType = schema.items ? schemaType(schema.items) : \"unknown\";\n return `Array<${itemType}>`;\n}\n\nfunction objectSchemaType(schema: any): string {\n const properties = Object.entries(schema.properties ?? {}).map(\n ([key, value]) =>\n `${JSON.stringify(key)}${schema.required?.includes(key) ? \"\" : \"?\"}: ${schemaType(value)};`,\n );\n const object = `{ ${properties.join(\" \")} }`;\n const patterns = Object.values(schema.patternProperties ?? {});\n if (patterns.length)\n return `${object} & Record<string, ${patterns.map(schemaType).join(\" | \")}>`;\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : schemaType(schema.additionalProperties);\n return `${object} & Record<string, ${valueType}>`;\n }\n return object;\n}\n"],"mappings":";;AAKA,SAAgB,uBAAuB,KAAuB;CAC5D,MAAM,EAAE,UAAU,WAAW,IAAI;CACjC,MAAM,WAAgC,OAAO,OAAO,IAAI;CACxD,MAAM,QAA6B,OAAO,OAAO,IAAI;CACrD,MAAM,kCAAkB,IAAI,IAAa;CACzC,KAAK,MAAM,WAAW,UACpB,aAAa,SAAS,QAAQ,UAAU,OAAO,eAAe;CAEhE,KAAK,MAAM,WAAW,UACpB,kBAAkB,SAAS,QAAQ,UAAU,OAAO,eAAe;CAErE,OA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,OAAO,MAAf;EACE,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK;EACL,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO,gBAAgB,MAAM;EAC/B,KAAK,UACH,OAAO,iBAAiB,MAAM;EAChC,KAAK,KAAA,GACH,OAAO;EACT,SACE,MAAM,IAAI,MAAM,sCAAsC,OAAO,KAAK,EAAE;CACxE;AACF;AAEA,SAAS,gBAAgB,QAAqB;CAC5C,IAAI,MAAM,QAAQ,OAAO,KAAK,GAC5B,OAAO,IAAI,OAAO,MAAM,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;CAErD,OAAO,SADU,OAAO,QAAQ,WAAW,OAAO,KAAK,IAAI,UAClC;AAC3B;AAEA,SAAS,iBAAiB,QAAqB;CAK7C,MAAM,SAAS,KAJI,OAAO,QAAQ,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,KACxD,CAAC,KAAK,WACL,GAAG,KAAK,UAAU,GAAG,IAAI,OAAO,UAAU,SAAS,GAAG,IAAI,KAAK,IAAI,IAAI,WAAW,KAAK,EAAE,EAEhE,CAAC,CAAC,KAAK,GAAG,EAAE;CACzC,MAAM,WAAW,OAAO,OAAO,OAAO,qBAAqB,CAAC,CAAC;CAC7D,IAAI,SAAS,QACX,OAAO,GAAG,OAAO,oBAAoB,SAAS,IAAI,UAAU,CAAC,CAAC,KAAK,KAAK,EAAE;CAC5E,IAAI,OAAO,sBAKT,OAAO,GAAG,OAAO,oBAHf,OAAO,yBAAyB,OAC5B,YACA,WAAW,OAAO,oBAAoB,EACG;CAEjD,OAAO;AACT"}
|
package/dist/compiler2.js
CHANGED
|
@@ -290,16 +290,8 @@ function analyzeApplication(services, prefix = "/api") {
|
|
|
290
290
|
}
|
|
291
291
|
}
|
|
292
292
|
for (const action of service.listActions()) {
|
|
293
|
-
const path = `${prefix}/${service.name}/${action.name}`;
|
|
294
|
-
add(service, action, "POST", path, "action");
|
|
295
|
-
if (/^(get|list|find|read)/.test(action.name)) add(service, action, "GET", path, "action");
|
|
296
|
-
if (action.config.path) {
|
|
297
|
-
if (action.config.method) add(service, action, action.config.method, action.config.path, "action");
|
|
298
|
-
else {
|
|
299
|
-
add(service, action, "GET", action.config.path, "action");
|
|
300
|
-
add(service, action, "POST", action.config.path, "action");
|
|
301
|
-
}
|
|
302
|
-
}
|
|
293
|
+
const path = action.config.path ?? `${prefix}/${service.name}/${action.name}`;
|
|
294
|
+
add(service, action, action.config.method ?? "POST", path, "action");
|
|
303
295
|
}
|
|
304
296
|
}
|
|
305
297
|
const reads = services.flatMap((service) => service.listResources().flatMap((resource) => {
|
package/dist/compiler2.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compiler2.js","names":["EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty"],"sources":["../src/action-handler.ts","../src/compiler/ir.ts","../src/compiler/emit.ts","../src/compiler/runtime.ts","../src/compiler.ts"],"sourcesContent":["import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n getCompiledCheck,\n buildErrorHelpers,\n} from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n const outputChecker = outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{ key: string; isNumber: boolean; isBoolean: boolean }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> =\n [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${plan.actionName}'`,\n 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import {\n type Service,\n type Action,\n describeResourceReads,\n type ResourceReadQueries,\n} from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, `${service.name}.${action.name}`);\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection],\n [\"create\", \"POST\", collection],\n [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item],\n [\"update\", \"PUT\", item],\n [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path = `${prefix}/${service.name}/${action.name}`;\n add(service, action, \"POST\", path, \"action\");\n if (/^(get|list|find|read)/.test(action.name))\n add(service, action, \"GET\", path, \"action\");\n if (action.config.path) {\n if (action.config.method)\n add(\n service,\n action,\n action.config.method,\n action.config.path,\n \"action\",\n );\n else {\n add(service, action, \"GET\", action.config.path, \"action\");\n add(service, action, \"POST\", action.config.path, \"action\");\n }\n }\n }\n }\n const reads = services.flatMap((service) =>\n service.listResources().flatMap((resource) => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n reads,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/cli/compiler\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string): never => {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${action}'`,\n 403,\n );\n },\n});\n","import {\n type Service,\n prepareResourceReads,\n prepareResourceWrites,\n} from \"@brickkit/core\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { emitHandlerFactory } from \"./compiler/emit\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\n\nexport { emitCompiledApplication, emitHandlerFactory } from \"./compiler/emit\";\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(\n (route) =>\n new Function(\n `return (${emitHandlerFactory(route)});`,\n )() as HandlerFactory,\n );\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n"],"mappings":";;AAWA,IAAI,UAAU;AACd,MAAMA,mBAAiB,OAAO,OAAO,CAAC,CAAC;AACvC,MAAMC,oBAAkB,IAAI,QAAQ,kBAAkB;AAEtD,SAASC,aAAW,KAAmB;CACrC,IAAI,OAAO,MAAM,OAAO;CACxB,KAAK,MAAM,KAAK,KAAK,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,SACX,WAAW,WAAW,KAAK,KAC3B,WAAW,SAAS,MAAM,KAC1B,WAAW,WAAW,MAAM,KAC5B,WAAW,SAAS,OAAO,KAC3B,WAAW,WAAW,MAAM,KAC5B,WAAW,WAAW,MAAM;CAE9B,MAAM,cAAc,OAAO,QAAQ;CACnC,MAAM,eAAe,OAAO,QAAQ;CACpC,MAAM,WAAW,QAAQ,WAAW;CACpC,MAAM,eAAe,cAChB,iBAAiB,WAAW,IAC7B,KAAA;CACJ,MAAM,gBAAgB,eACjB,iBAAiB,YAAY,IAC9B,KAAA;CAEJ,IAAI;CAGJ,IAAI,eAAe,OAAQ,YAAoB,eAAe,UAAU;EACtE,MAAM,OACJ,CAAC;EACH,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAC9B,YAAoB,UACvB,GAAsB;GACpB,MAAM,OAAO,MAAM;GACnB,IAAI,SAAS,YAAY,SAAS,WAChC,KAAK,KAAK;IAAE;IAAK,UAAU;IAAM,WAAW;GAAM,CAAC;QAC9C,IAAI,SAAS,WAClB,KAAK,KAAK;IAAE;IAAK,UAAU;IAAO,WAAW;GAAK,CAAC;EAEvD;EACA,IAAI,KAAK,SAAS,GAAG,YAAY;CACnC;CAEA,MAAM,cAAc,QAAQ,SAAS;C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AK,UAAU,EAAE,GACnD,MAAM,IAAI,MACR,8FACF;CACF,KAAK,MAAM,WAAW,UAAU;EAC9B,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACA,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
|
|
1
|
+
{"version":3,"file":"compiler2.js","names":["EMPTY_SERVICES","DEFAULT_REQUEST","isNonEmpty"],"sources":["../src/action-handler.ts","../src/compiler/ir.ts","../src/compiler/emit.ts","../src/compiler/runtime.ts","../src/compiler.ts"],"sourcesContent":["import {\n type Service,\n type Action,\n type Logger,\n type CompiledRoutePlan,\n ValidationError,\n ActionExecutionError,\n getCompiledCheck,\n buildErrorHelpers,\n} from \"@brickkit/core\";\n\nlet _srvSeq = 0;\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\n\nfunction isNonEmpty(obj: any): boolean {\n if (obj == null) return false;\n for (const _ in obj) return true;\n return false;\n}\n\nexport function compileRoutePlan(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n): CompiledRoutePlan {\n const actionName = action.name;\n const serviceName = service.name;\n const isGetLike =\n method === \"GET\" ||\n actionName.startsWith(\"get\") ||\n actionName.endsWith(\".get\") ||\n actionName.startsWith(\"list\") ||\n actionName.endsWith(\".list\") ||\n actionName.startsWith(\"find\") ||\n actionName.startsWith(\"read\");\n\n const inputSchema = action.config?.input;\n const outputSchema = action.config?.output;\n const hasInput = Boolean(inputSchema);\n const inputChecker = inputSchema\n ? (getCompiledCheck(inputSchema) as any)\n : undefined;\n const outputChecker = outputSchema\n ? (getCompiledCheck(outputSchema) as any)\n : undefined;\n\n let coercions:\n | Array<{ key: string; isNumber: boolean; isBoolean: boolean }>\n | undefined;\n if (inputSchema && typeof (inputSchema as any).properties === \"object\") {\n const list: Array<{ key: string; isNumber: boolean; isBoolean: boolean }> =\n [];\n for (const [key, prop] of Object.entries(\n (inputSchema as any).properties,\n ) as [string, any][]) {\n const type = prop?.type;\n if (type === \"number\" || type === \"integer\") {\n list.push({ key, isNumber: true, isBoolean: false });\n } else if (type === \"boolean\") {\n list.push({ key, isNumber: false, isBoolean: true });\n }\n }\n if (list.length > 0) coercions = list;\n }\n\n const contextHook = service.options?.context;\n const hasContextHook = typeof contextHook === \"function\";\n\n const authorize = action.config?.authorize;\n const hasAuthorize = typeof authorize === \"function\";\n\n const execute = action.config?.execute;\n\n const tag = `[${serviceName}:${actionName}]`;\n const logger: Logger = {\n info: (...args) => console.log(tag, ...args),\n warn: (...args) => console.warn(tag, ...args),\n error: (...args) => console.error(tag, ...args),\n debug: (...args) => console.debug(tag, ...args),\n };\n\n const errorBuilder =\n (action as any).errorHelpers ?? buildErrorHelpers(action.config?.errors);\n const cachedDb = service.getDb();\n\n return {\n service,\n action,\n actionName,\n serviceName,\n routePath,\n method,\n isGetLike,\n hasInput,\n hasContextHook,\n contextHook,\n hasAuthorize,\n authorize,\n execute,\n inputChecker,\n outputChecker,\n coercions,\n logger,\n errorBuilder,\n cachedDb,\n };\n}\n\nexport async function executeCompiledRoute(\n plan: CompiledRoutePlan,\n elysiaCtx: any,\n) {\n const { params, body, query, headers, request, set } = elysiaCtx;\n const seq = (++_srvSeq).toString(36);\n const traceId = (headers && headers[\"x-trace-id\"]) || `tr_${seq}`;\n const requestId = (headers && headers[\"x-request-id\"]) || `req_${seq}`;\n\n if (set?.headers) {\n set.headers[\"x-trace-id\"] = traceId;\n set.headers[\"x-request-id\"] = requestId;\n }\n\n let input: any;\n if (plan.hasInput) {\n let coercedQuery = query;\n if (query && plan.coercions && plan.coercions.length > 0) {\n coercedQuery = { ...query };\n for (let i = 0; i < plan.coercions.length; i++) {\n const c = plan.coercions[i];\n const val = query[c.key];\n if (val !== undefined) {\n if (c.isNumber) {\n const num = Number(val);\n if (!isNaN(num)) coercedQuery[c.key] = num;\n } else if (c.isBoolean) {\n if (val === \"true\" || val === \"1\") coercedQuery[c.key] = true;\n else if (val === \"false\" || val === \"0\")\n coercedQuery[c.key] = false;\n }\n }\n }\n }\n\n const hasP = isNonEmpty(params);\n const hasB = isNonEmpty(body);\n const hasQ = isNonEmpty(coercedQuery);\n\n if (plan.isGetLike) {\n if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP && !hasQ && !hasB) {\n input = params;\n } else if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasQ || hasP || hasB) {\n input = Object.assign({}, coercedQuery, params, body);\n }\n } else {\n if (hasB && !hasP && !hasQ) {\n input = body;\n } else if (hasP && !hasB && !hasQ) {\n input = params;\n } else if (hasQ && !hasP && !hasB) {\n input = coercedQuery;\n } else if (hasP || hasB || hasQ) {\n input = Object.assign({}, params, body, coercedQuery);\n }\n }\n }\n\n const standardRequest =\n request instanceof Request ? request : DEFAULT_REQUEST;\n\n const ctx: any = {\n request: standardRequest,\n traceId,\n requestId,\n db: plan.cachedDb ?? plan.service.getDb(),\n logger: plan.logger,\n services: EMPTY_SERVICES,\n metadata: { headers },\n _resolved: true,\n };\n\n try {\n if (plan.hasContextHook) {\n const extra = plan.contextHook!(ctx);\n const resolved = extra instanceof Promise ? await extra : extra;\n if (resolved) {\n Object.assign(ctx, resolved);\n }\n }\n\n if (input === undefined && plan.action.config?.input?.type === \"object\") {\n input = {};\n }\n\n if (plan.hasInput && plan.inputChecker) {\n if (!plan.inputChecker.Check(input)) {\n const errors = Array.from(plan.inputChecker.Errors(input)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' input`,\n errors,\n );\n }\n }\n\n if (plan.hasAuthorize) {\n const authRes = plan.authorize!({\n ctx,\n input,\n user: ctx.user,\n });\n const isAuthorized = authRes instanceof Promise ? await authRes : authRes;\n if (!isAuthorized) {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${plan.actionName}'`,\n 403,\n );\n }\n }\n\n const execRes = plan.execute({ input, ctx, error: plan.errorBuilder });\n const result = execRes instanceof Promise ? await execRes : execRes;\n\n if (plan.outputChecker) {\n if (!plan.outputChecker.Check(result)) {\n const errors = Array.from(plan.outputChecker.Errors(result)).map(\n (err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }),\n );\n throw new ValidationError(\n `Validation failed for action '${plan.actionName}' output`,\n errors,\n 500,\n );\n }\n }\n\n return result;\n } catch (err: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err.message || \"An unexpected error occurred\",\n status: 500,\n };\n }\n}\n\nexport function createActionHandler(\n service: Service,\n action: Action,\n routePath: string,\n method?: string,\n) {\n const plan = compileRoutePlan(service, action, routePath, method);\n return (elysiaCtx: any) => executeCompiledRoute(plan, elysiaCtx);\n}\n","import {\n type Service,\n type Action,\n describeResourceReads,\n type ResourceReadQueries,\n} from \"@brickkit/core\";\n\nexport type RouteMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\nexport interface RouteIR {\n readonly method: RouteMethod;\n readonly path: string;\n readonly service: string;\n readonly action: string;\n readonly kind: \"action\" | \"resource\";\n readonly input: boolean;\n readonly output: boolean;\n readonly context: boolean;\n readonly authorize: boolean;\n readonly inputPrecedence: readonly (\"query\" | \"params\" | \"body\")[];\n readonly coercions: readonly {\n readonly key: string;\n readonly type: \"number\" | \"boolean\";\n }[];\n /** JSON projection for inspection and stale-artifact detection, not runtime validation. */\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n}\nexport interface BrickIR {\n readonly version: 1;\n readonly target: \"bun-elysia\";\n readonly prefix: string;\n readonly services: readonly string[];\n readonly routes: readonly RouteIR[];\n readonly reads: readonly ResourceReadQueries[];\n readonly diagnostics: readonly string[];\n}\nexport interface RouteBinding {\n readonly service: Service<any, any>;\n readonly action: Action<any, any, any, any>;\n}\n\nexport function freezeIR<T>(value: T): T {\n if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n for (const child of Object.values(value)) freezeIR(child);\n Object.freeze(value);\n }\n return value;\n}\n\nfunction schemaSnapshot(schema: unknown): unknown {\n return schema === undefined ? undefined : JSON.parse(JSON.stringify(schema));\n}\n\nexport function analyzeApplication(\n services: Service<any, any>[],\n prefix = \"/api\",\n) {\n if (!prefix.startsWith(\"/\"))\n throw new Error(\"Brick compiler: prefix must start with '/'\");\n const names = new Set<string>();\n for (const service of services) {\n if (names.has(service.name))\n throw new Error(`Brick compiler: duplicate service '${service.name}'`);\n names.add(service.name);\n service.build();\n }\n const routes: RouteIR[] = [];\n const bindings: RouteBinding[] = [];\n const registered = new Map<string, string>();\n const diagnostics: string[] = [];\n const add = (\n service: Service<any, any>,\n action: Action<any, any, any, any>,\n method: RouteMethod,\n path: string,\n kind: RouteIR[\"kind\"],\n ) => {\n if (!path.startsWith(\"/\"))\n throw new Error(`Brick compiler: invalid route '${method} ${path}'`);\n const key = `${method} ${path}`;\n const previous = registered.get(key);\n if (previous) {\n diagnostics.push(\n `${key}: '${service.name}.${action.name}' shadowed by '${previous}' (first registration wins)`,\n );\n return;\n }\n if (typeof action.config.execute !== \"function\")\n throw new Error(\n `Brick compiler: '${service.name}.${action.name}' has no execute handler`,\n );\n registered.set(key, `${service.name}.${action.name}`);\n const readLike =\n method === \"GET\" ||\n action.name.startsWith(\"get\") ||\n action.name.endsWith(\".get\") ||\n action.name.startsWith(\"list\") ||\n action.name.endsWith(\".list\") ||\n action.name.startsWith(\"find\") ||\n action.name.startsWith(\"read\");\n const coercions: { key: string; type: \"number\" | \"boolean\" }[] = [];\n for (const [key, prop] of Object.entries(\n action.config.input?.properties ?? {},\n ) as [string, any][]) {\n if (prop.type === \"number\" || prop.type === \"integer\")\n coercions.push({ key, type: \"number\" });\n else if (prop.type === \"boolean\")\n coercions.push({ key, type: \"boolean\" });\n }\n routes.push({\n method,\n path,\n service: service.name,\n action: action.name,\n kind,\n input: Boolean(action.config.input),\n output: Boolean(action.config.output),\n context: typeof service.options.context === \"function\",\n authorize: typeof action.config.authorize === \"function\",\n inputPrecedence: readLike\n ? [\"query\", \"params\", \"body\"]\n : [\"params\", \"body\", \"query\"],\n coercions,\n inputSchema: schemaSnapshot(action.config.input),\n outputSchema: schemaSnapshot(action.config.output),\n });\n bindings.push({ service, action });\n };\n for (const service of services) {\n for (const resource of service.listResources()) {\n const collection = `${prefix}/${resource.name}`;\n const item = `${collection}/:id`;\n for (const [operation, method, path] of [\n [\"list\", \"GET\", collection],\n [\"create\", \"POST\", collection],\n [\"get\", \"GET\", item],\n [\"update\", \"PATCH\", item],\n [\"update\", \"PUT\", item],\n [\"delete\", \"DELETE\", item],\n ] as const) {\n const action = resource.actions[operation];\n if (action) add(service, action, method, path, \"resource\");\n }\n }\n for (const action of service.listActions()) {\n const path =\n action.config.path ?? `${prefix}/${service.name}/${action.name}`;\n add(service, action, action.config.method ?? \"POST\", path, \"action\");\n }\n }\n const reads = services.flatMap((service) =>\n service.listResources().flatMap((resource) => {\n const queries = describeResourceReads(service, resource);\n return queries ? [queries] : [];\n }),\n );\n const ir: BrickIR = freezeIR({\n version: 1,\n target: \"bun-elysia\",\n prefix,\n services: [...names],\n routes,\n reads,\n diagnostics,\n });\n return { ir, bindings };\n}\n","import type { BrickIR, RouteIR } from \"./ir\";\n\n/** Emits framework code only. User callbacks remain closures bound separately. */\nexport function emitHandlerFactory(route: RouteIR): string {\n const name = JSON.stringify(route.action);\n const fields = route.input\n ? \"params, body, query, headers, request, set\"\n : \"headers, request, set\";\n const input: string[] = [\"let input;\"];\n if (route.input) {\n input.push(\"let coercedQuery = query;\");\n if (route.coercions.length) {\n input.push(\"if (query) {\", \"coercedQuery = { ...query };\");\n for (const [index, coercion] of route.coercions.entries()) {\n const key = JSON.stringify(coercion.key);\n input.push(`const v${index} = query[${key}];`);\n if (coercion.type === \"number\")\n input.push(\n `if (v${index} !== undefined) { const n${index} = Number(v${index}); if (!Number.isNaN(n${index})) coercedQuery[${key}] = n${index}; }`,\n );\n else\n input.push(\n `if (v${index} === \"true\" || v${index} === \"1\") coercedQuery[${key}] = true; else if (v${index} === \"false\" || v${index} === \"0\") coercedQuery[${key}] = false;`,\n );\n }\n input.push(\"}\");\n }\n input.push(\n `input = mergeInput(${route.inputPrecedence.map((source) => (source === \"query\" ? \"coercedQuery\" : source)).join(\", \")});`,\n );\n if ((route.inputSchema as { type?: string } | undefined)?.type === \"object\")\n input.push(\"input ??= {};\");\n }\n const asyncStages = route.context || route.authorize;\n const context = route.context\n ? \"const extra = await contextHook(ctx); if (extra) Object.assign(ctx, extra);\"\n : \"\";\n const validation = route.input\n ? `validate(inputChecker, input, ${name}, \"input\");`\n : \"\";\n const authorization = route.authorize\n ? `if (!await authorize({ ctx, input, user: ctx.user })) deny(${name});`\n : \"\";\n const output = route.output\n ? `validate(outputChecker, result, ${name}, \"output\");`\n : \"\";\n const execute = asyncStages\n ? `const result = await execute({ input, ctx, error: errorBuilder });\\n${output}\\nreturn result;`\n : `const result = execute({ input, ctx, error: errorBuilder });\nif (isThenable(result)) return Promise.resolve(result).then(value => {\n ${route.output ? `validate(outputChecker, value, ${name}, \"output\");` : \"\"}\n return value;\n}).catch(err => mapError(err, set));\n${output}\nreturn result;`;\n return `function bindAction(binding, runtime) {\nconst { execute, contextHook, authorize, inputChecker, outputChecker, errorBuilder, logger, cachedDb, service } = binding;\nconst { nextSequence, defaultRequest, emptyServices, mergeInput, validate, deny, mapError, isThenable } = runtime;\nreturn ${asyncStages ? \"async \" : \"\"}function brickAction({ ${fields} }) {\nconst seq = nextSequence();\nconst traceId = (headers && headers[\"x-trace-id\"]) || \"tr_\" + seq;\nconst requestId = (headers && headers[\"x-request-id\"]) || \"req_\" + seq;\nif (set?.headers) { set.headers[\"x-trace-id\"] = traceId; set.headers[\"x-request-id\"] = requestId; }\n${input.join(\"\\n\")}\nconst ctx = { request: request instanceof Request ? request : defaultRequest, traceId, requestId,\n db: cachedDb ?? service.getDb(), logger, services: emptyServices, metadata: { headers }, _resolved: true };\ntry {\n${context}\n${validation}\n${authorization}\n${execute}\n} catch (err) { return mapError(err, set); }\n};\n}`;\n}\n\n/** An ES module of real JS functions; it never stringifies application callbacks. */\nexport function emitCompiledApplication(\n ir: BrickIR,\n runtimeImport = \"@brickkit/cli/compiler\",\n): string {\n return `// Generated by Brick compiler v1. Rebuild after changing application definitions.\\nimport { bindCompiledApplication } from ${JSON.stringify(runtimeImport)};\\nexport const ir = JSON.parse(${JSON.stringify(JSON.stringify(ir))});\\nconst factories = [\\n${ir.routes.map(emitHandlerFactory).join(\",\\n\")}\\n];\\nexport function bind(services) { return bindCompiledApplication(ir, services, factories); }\\n`;\n}\n","import {\n ValidationError,\n ActionExecutionError,\n type CompiledRoutePlan,\n} from \"@brickkit/core\";\n\nexport type CompiledHandler = (context: any) => unknown | Promise<unknown>;\nexport type HandlerFactory = (\n binding: CompiledRoutePlan,\n runtime: typeof compilerRuntime,\n) => CompiledHandler;\n\nconst EMPTY_SERVICES = Object.freeze({});\nconst DEFAULT_REQUEST = new Request(\"http://localhost\");\nlet sequence = 0;\n\nfunction isNonEmpty(value: any): boolean {\n if (value == null) return false;\n for (const _ in value) return true;\n return false;\n}\n\n/** Retains Brick's existing source precedence and treatment of empty bodies. */\nfunction mergeInput(first: any, second: any, third: any) {\n const a = isNonEmpty(first),\n b = isNonEmpty(second),\n c = isNonEmpty(third);\n if (a && !b && !c) return first;\n if (b && !a && !c) return second;\n if (c && !a && !b) return third;\n if (a || b || c) return Object.assign({}, first, second, third);\n return undefined;\n}\n\nfunction validate(\n check: NonNullable<CompiledRoutePlan[\"inputChecker\"]>,\n value: unknown,\n action: string,\n stage: \"input\" | \"output\",\n) {\n if (check.Check(value)) return;\n const errors = Array.from(check.Errors(value)).map((err: any) => ({\n path: err.path,\n message: err.message,\n value: err.value,\n }));\n throw new ValidationError(\n `Validation failed for action '${action}' ${stage}`,\n errors,\n stage === \"output\" ? 500 : 400,\n );\n}\n\nfunction mapError(err: any, set: any) {\n if (err instanceof ValidationError || err instanceof ActionExecutionError) {\n set.status = err.status || 400;\n return err.toJSON();\n }\n set.status = 500;\n return {\n name: \"InternalServerError\",\n message: err?.message || \"An unexpected error occurred\",\n status: 500,\n };\n}\n\nexport const compilerRuntime = Object.freeze({\n emptyServices: EMPTY_SERVICES,\n defaultRequest: DEFAULT_REQUEST,\n nextSequence: () => (++sequence).toString(36),\n mergeInput,\n validate,\n mapError,\n isThenable: (value: any): boolean =>\n value != null && typeof value.then === \"function\",\n deny: (action: string): never => {\n throw new ActionExecutionError(\n \"UNAUTHORIZED\",\n `Access denied for action '${action}'`,\n 403,\n );\n },\n});\n","import {\n type Service,\n prepareResourceReads,\n prepareResourceWrites,\n} from \"@brickkit/core\";\nimport { compileRoutePlan, executeCompiledRoute } from \"./action-handler\";\nimport {\n analyzeApplication,\n freezeIR,\n type BrickIR,\n type RouteIR,\n} from \"./compiler/ir\";\nimport { emitHandlerFactory } from \"./compiler/emit\";\nimport {\n compilerRuntime,\n type CompiledHandler,\n type HandlerFactory,\n} from \"./compiler/runtime\";\n\nexport { emitCompiledApplication, emitHandlerFactory } from \"./compiler/emit\";\nexport type { BrickIR, RouteIR, RouteMethod } from \"./compiler/ir\";\nexport type { CompiledHandler, HandlerFactory } from \"./compiler/runtime\";\nexport interface CompiledRoute {\n readonly ir: RouteIR;\n readonly handler: CompiledHandler;\n}\nexport interface CompiledApplication {\n readonly ir: BrickIR;\n readonly routes: readonly CompiledRoute[];\n}\n\nfunction bindAnalyzed(\n ir: BrickIR,\n bindings: ReturnType<typeof analyzeApplication>[\"bindings\"],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (factories.length !== ir.routes.length)\n throw new Error(\"Brick compiler: handler factory count does not match IR\");\n const routes = ir.routes.map((route, index) => {\n const { service, action } = bindings[index]!;\n const plan = Object.freeze(\n compileRoutePlan(service, action, route.path, route.method),\n );\n const handler = factories[index]!(plan, compilerRuntime);\n return Object.freeze({ ir: route, handler });\n });\n return Object.freeze({ ir: freezeIR(ir), routes: Object.freeze(routes) });\n}\n\n/** Startup compiler: analyzes once, generates JS once, then binds live callbacks. */\nexport function compileBrickApplication(options: {\n services: Service<any, any>[];\n prefix?: string;\n mode?: \"specialized\" | \"generic\";\n}): CompiledApplication {\n const { ir, bindings } = analyzeApplication(options.services, options.prefix);\n const factories: HandlerFactory[] =\n options.mode === \"generic\"\n ? ir.routes.map(\n () => (plan) => (context) => executeCompiledRoute(plan, context),\n )\n : ir.routes.map(\n (route) =>\n new Function(\n `return (${emitHandlerFactory(route)});`,\n )() as HandlerFactory,\n );\n if (options.mode !== \"generic\")\n for (const service of options.services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, bindings, factories);\n}\n\n/** Build artifact binder: consumes emitted functions, with no runtime handler code generation. */\nexport function bindCompiledApplication(\n ir: BrickIR,\n services: Service<any, any>[],\n factories: readonly HandlerFactory[],\n): CompiledApplication {\n if (ir.version !== 1 || ir.target !== \"bun-elysia\")\n throw new Error(\n \"Brick compiler: unsupported IR version or target; rebuild the application\",\n );\n const analyzed = analyzeApplication(services, ir.prefix);\n if (JSON.stringify(analyzed.ir) !== JSON.stringify(ir))\n throw new Error(\n \"Brick compiler: application definitions differ from the compiled IR; rebuild the application\",\n );\n for (const service of services) {\n prepareResourceReads(service);\n prepareResourceWrites(service);\n }\n return bindAnalyzed(ir, analyzed.bindings, factories);\n}\n"],"mappings":";;AAWA,IAAI,UAAU;AACd,MAAMA,mBAAiB,OAAO,OAAO,CAAC,CAAC;AACvC,MAAMC,oBAAkB,IAAI,QAAQ,kBAAkB;AAEtD,SAASC,aAAW,KAAmB;CACrC,IAAI,OAAO,MAAM,OAAO;CACxB,KAAK,MAAM,KAAK,KAAK,OAAO;CAC5B,OAAO;AACT;AAEA,SAAgB,iBACd,SACA,QACA,WACA,QACmB;CACnB,MAAM,aAAa,OAAO;CAC1B,MAAM,cAAc,QAAQ;CAC5B,MAAM,YACJ,WAAW,SACX,WAAW,WAAW,KAAK,KAC3B,WAAW,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AAM,OAAO,CACjE,IACA,GAAG,OAAO,KACP,UACC,IAAI,SACF,WAAW,mBAAmB,KAAK,EAAE,GACvC,CAAC,CAAC,CACN;CACN,IAAI,QAAQ,SAAS,WACnB,KAAK,MAAM,WAAW,QAAQ,UAAU;EACtC,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACF,OAAO,aAAa,IAAI,UAAU,SAAS;AAC7C;;AAGA,SAAgB,wBACd,IACA,UACA,WACqB;CACrB,IAAI,GAAG,YAAY,KAAK,GAAG,WAAW,cACpC,MAAM,IAAI,MACR,2EACF;CACF,MAAM,WAAW,mBAAmB,UAAU,GAAG,MAAM;CACvD,IAAI,KAAK,UAAU,SAAS,EAAE,MAAM,KAAK,UAAU,EAAE,GACnD,MAAM,IAAI,MACR,8FACF;CACF,KAAK,MAAM,WAAW,UAAU;EAC9B,qBAAqB,OAAO;EAC5B,sBAAsB,OAAO;CAC/B;CACA,OAAO,aAAa,IAAI,SAAS,UAAU,SAAS;AACtD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -75,6 +75,11 @@ interface EndpointDefinition {
|
|
|
75
75
|
}
|
|
76
76
|
/** The app object returned by `brick`: Elysia plus `endpoint()`. */
|
|
77
77
|
type BrickApp = Elysia<any, any, any, any, any, any, any> & {
|
|
78
|
+
/** Service definitions and prefix selected when this app was constructed. */
|
|
79
|
+
readonly definition: {
|
|
80
|
+
readonly services: readonly Service<any, any>[];
|
|
81
|
+
readonly prefix: string;
|
|
82
|
+
};
|
|
78
83
|
/** Register a raw endpoint (outside the JSON action mesh). */
|
|
79
84
|
endpoint(def: EndpointDefinition): void;
|
|
80
85
|
/** All endpoints registered via `endpoint()` (declaration order). */
|
|
@@ -108,42 +113,6 @@ interface CreateServerOptions {
|
|
|
108
113
|
}
|
|
109
114
|
export declare function brick(options?: CreateServerOptions): BrickApp;
|
|
110
115
|
//#endregion
|
|
111
|
-
//#region src/contract.d.ts
|
|
112
|
-
/**
|
|
113
|
-
* Options for {@link brickFromContract}: everything `brick()` accepts except
|
|
114
|
-
* `services`, which is derived from the contract itself.
|
|
115
|
-
*/
|
|
116
|
-
type BrickFromContractOptions = Omit<CreateServerOptions, "services">;
|
|
117
|
-
/**
|
|
118
|
-
* Contract-first server: builds the `brick()` app from the same contract
|
|
119
|
-
* object that types the frontend client, so services are declared once.
|
|
120
|
-
*
|
|
121
|
-
* ```ts
|
|
122
|
-
* // server.ts (backend, single source of truth)
|
|
123
|
-
* export const contract = defineAppContract({
|
|
124
|
-
* page: { list: listPages, create: createPage },
|
|
125
|
-
* billing: { charge: chargeAction },
|
|
126
|
-
* });
|
|
127
|
-
* export type AppServer = typeof contract;
|
|
128
|
-
*
|
|
129
|
-
* export const app = brickFromContract(contract, { port: 4000 });
|
|
130
|
-
* ```
|
|
131
|
-
*
|
|
132
|
-
* ```ts
|
|
133
|
-
* // frontend (type-only import, erased at build)
|
|
134
|
-
* import type { AppServer } from "./server";
|
|
135
|
-
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
136
|
-
* ```
|
|
137
|
-
*
|
|
138
|
-
* Services are resolved through the global registry by each action's
|
|
139
|
-
* `serviceName`, so every definition in the contract must be bound to a service
|
|
140
|
-
* (via `service.action(...)` or `service.tool(...)`). Only HTTP actions
|
|
141
|
-
* registered on that service produce routes. An
|
|
142
|
-
* error names the offending action when it is unbound or its service was
|
|
143
|
-
* never registered.
|
|
144
|
-
*/
|
|
145
|
-
export declare function brickFromContract<TContract extends Record<string, any>>(contract: TContract, options?: BrickFromContractOptions): BrickApp;
|
|
146
|
-
//#endregion
|
|
147
116
|
//#region src/runner.d.ts
|
|
148
117
|
interface DevServerOptions {
|
|
149
118
|
port?: number;
|
|
@@ -168,5 +137,9 @@ export declare function buildApplication(options: BuildApplicationOptions): Prom
|
|
|
168
137
|
ir: BrickIR;
|
|
169
138
|
}>;
|
|
170
139
|
//#endregion
|
|
171
|
-
|
|
140
|
+
//#region src/client-contract.d.ts
|
|
141
|
+
/** Generate browser metadata and transport types from the app's selected services. */
|
|
142
|
+
export declare function generateClientContract(app: BrickApp): string;
|
|
143
|
+
//#endregion
|
|
144
|
+
export { type BrickApp, type BrickIR, type BuildApplicationOptions, type CompiledApplication, type CreateServerOptions, type DevServerOptions, type EndpointContext, type EndpointDefinition, type EndpointLogger, type EndpointMethod, type ReferenceOptions, type RequestLoggingOptions, type RouteIR, bindCompiledApplication, compileBrickApplication, emitCompiledApplication };
|
|
172
145
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["_$__endpoints0.BrickApp","_$__compiler0.BrickIR"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["_$__endpoints0.BrickApp","_$__compiler0.BrickIR"],"sources":["../src/request-logger.ts","../src/docs.ts","../src/endpoints.ts","../src/server.ts","../src/runner.ts","../src/build.ts","../src/client-contract.ts"],"mappings":";;;;UAEiB;EACf;EACA,UAAU;;;;;;;;;;;;;;wBAoCI,qBAAqB,OAAM,wBAA6B;;;UCtCvD;EACf;EACA;EACA;;;wBAIc,eAAe,iBAAiB;;wBAwBhC,gBAAgB,OAAM,mBAAwB;;wBAa9C,uBACd,KAAK,QACL,OAAM,mBACL;;;KC7CS;;UAGK;EACf,UAAU;EACV,UAAU;EACV,WAAW;EACX,WAAW;;;UAII;EACf,QAAQ;EACR,OAAO;EACP;EACA,SAAS;EACT,SAAS;;EAET;IAAO;IAAiB,SAAS;;;EAEjC;EACA,QAAQ;EACR;EACA;;UAGe;EACf,QAAQ;;EAER;EACA,UAAU,KAAK,8BAA8B;;EAE7C,UAAU;;EAEV,WAAW;EACX;EACA;EACA;;;KA6HU,WAAW;;WAEZ;aACE,mBAAmB;aACnB;;;EAGX,SAAS,KAAK;;EAEd,iBAAiB;;;;UCrJF;EACf;;EAEA;;EAEA,cAAc;EACd,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,2BAA2B;EAC3B,sBAAsB;EACtB;IAAY,SAAS;IAAc;;;EAEnC,YAAY;;wBASE,MAAM,UAAS,sBAA2B;;;UCjDzC;EACf;EACA;EACA;;wBAGoB,eAAe,UAAS,mBAAqB,QAArBA;;;UCL7B;;EAEf;EACA;EACA;EACA;EACA;;;wBAIoB,iBAAiB,SAAS,0BAAuB;;;MAAvBC;;;;;wBCXhC,uBAAuB,KAAK"}
|
package/dist/index.js
CHANGED
|
@@ -1,88 +1,4 @@
|
|
|
1
1
|
import { n as compileBrickApplication, r as emitCompiledApplication, t as bindCompiledApplication } from "./compiler2.js";
|
|
2
2
|
import { a as registerReferenceRoute, i as referencePlugin, n as startDevServer, o as scalarDocsHTML, r as brick, s as requestLoggingPlugin, t as buildApplication } from "./build.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
function isAction(value) {
|
|
6
|
-
return typeof value === "function" && !!value.config && typeof value.config.execute === "function";
|
|
7
|
-
}
|
|
8
|
-
function isService(value) {
|
|
9
|
-
return !!value && typeof value === "object" && typeof value.listActions === "function" && value.actions instanceof Map;
|
|
10
|
-
}
|
|
11
|
-
function isResource(value) {
|
|
12
|
-
return !!value && typeof value === "object" && !isService(value) && !!value.actions && typeof value.actions === "object";
|
|
13
|
-
}
|
|
14
|
-
function isPlainObject(value) {
|
|
15
|
-
if (!value || typeof value !== "object") return false;
|
|
16
|
-
const proto = Object.getPrototypeOf(value);
|
|
17
|
-
return proto === Object.prototype || proto === null;
|
|
18
|
-
}
|
|
19
|
-
/** Collects definitions to resolve services; each service registers its own HTTP actions. */
|
|
20
|
-
function collectActions(node, out) {
|
|
21
|
-
if (isAction(node)) {
|
|
22
|
-
out.push(node);
|
|
23
|
-
return;
|
|
24
|
-
}
|
|
25
|
-
if (isService(node)) {
|
|
26
|
-
out.push(...node.listActions(), ...node.listTools?.() ?? []);
|
|
27
|
-
return;
|
|
28
|
-
}
|
|
29
|
-
if (isResource(node)) {
|
|
30
|
-
out.push(...Object.values(node.actions));
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
if (isPlainObject(node)) for (const value of Object.values(node)) collectActions(value, out);
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Contract-first server: builds the `brick()` app from the same contract
|
|
37
|
-
* object that types the frontend client, so services are declared once.
|
|
38
|
-
*
|
|
39
|
-
* ```ts
|
|
40
|
-
* // server.ts (backend, single source of truth)
|
|
41
|
-
* export const contract = defineAppContract({
|
|
42
|
-
* page: { list: listPages, create: createPage },
|
|
43
|
-
* billing: { charge: chargeAction },
|
|
44
|
-
* });
|
|
45
|
-
* export type AppServer = typeof contract;
|
|
46
|
-
*
|
|
47
|
-
* export const app = brickFromContract(contract, { port: 4000 });
|
|
48
|
-
* ```
|
|
49
|
-
*
|
|
50
|
-
* ```ts
|
|
51
|
-
* // frontend (type-only import, erased at build)
|
|
52
|
-
* import type { AppServer } from "./server";
|
|
53
|
-
* const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
|
|
54
|
-
* ```
|
|
55
|
-
*
|
|
56
|
-
* Services are resolved through the global registry by each action's
|
|
57
|
-
* `serviceName`, so every definition in the contract must be bound to a service
|
|
58
|
-
* (via `service.action(...)` or `service.tool(...)`). Only HTTP actions
|
|
59
|
-
* registered on that service produce routes. An
|
|
60
|
-
* error names the offending action when it is unbound or its service was
|
|
61
|
-
* never registered.
|
|
62
|
-
*/
|
|
63
|
-
function brickFromContract(contract, options = {}) {
|
|
64
|
-
if (!contract || typeof contract !== "object") throw new Error("[Brick-TS] brickFromContract: `contract` must be an object of actions, resources, or services.");
|
|
65
|
-
const actions = [];
|
|
66
|
-
collectActions(contract, actions);
|
|
67
|
-
if (actions.length === 0) throw new Error("[Brick-TS] brickFromContract: contract contains no actions.");
|
|
68
|
-
const unbound = actions.filter((action) => !action.serviceName);
|
|
69
|
-
if (unbound.length > 0) throw new Error(`[Brick-TS] brickFromContract: actions not bound to a service (define them via service.action(...)): ${unbound.map((action) => `'${action.name}'`).join(", ")}.`);
|
|
70
|
-
const services = [];
|
|
71
|
-
const seen = /* @__PURE__ */ new Set();
|
|
72
|
-
for (const action of actions) {
|
|
73
|
-
const name = action.serviceName;
|
|
74
|
-
if (seen.has(name)) continue;
|
|
75
|
-
seen.add(name);
|
|
76
|
-
const service = getGlobalRegistry().get(name);
|
|
77
|
-
if (!service) throw new Error(`[Brick-TS] brickFromContract: service '${name}' (used by action '${action.name}') is not registered.`);
|
|
78
|
-
services.push(service);
|
|
79
|
-
}
|
|
80
|
-
return brick({
|
|
81
|
-
...options,
|
|
82
|
-
services
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
//#endregion
|
|
86
|
-
export { bindCompiledApplication, brick, brickFromContract, buildApplication, compileBrickApplication, emitCompiledApplication, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
|
|
87
|
-
|
|
88
|
-
//# sourceMappingURL=index.js.map
|
|
3
|
+
import { t as generateClientContract } from "./client-contract.js";
|
|
4
|
+
export { bindCompiledApplication, brick, buildApplication, compileBrickApplication, emitCompiledApplication, generateClientContract, referencePlugin, registerReferenceRoute, requestLoggingPlugin, scalarDocsHTML, startDevServer };
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
//#region src/vite.d.ts
|
|
3
|
+
export interface BrickClientPluginOptions {
|
|
4
|
+
/** Any module whose default export is a BrickApp; do not call listen() there. */
|
|
5
|
+
entry: string;
|
|
6
|
+
/** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */
|
|
7
|
+
output?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Load a BrickApp through Vite's server module graph, including dependency HMR. */
|
|
10
|
+
export declare function brickClient(options: BrickClientPluginOptions): Plugin;
|
|
11
|
+
//#endregion
|
|
12
|
+
//# sourceMappingURL=vite.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;iBAciB;;EAEf;;EAEA;;;wBAIc,YAAY,SAAS,2BAA2B"}
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { t as generateClientContract } from "./client-contract.js";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, resolve } from "node:path";
|
|
4
|
+
import { createServer, isRunnableDevEnvironment, normalizePath } from "vite";
|
|
5
|
+
import { ModuleRunner } from "vite/module-runner";
|
|
6
|
+
//#region src/vite.ts
|
|
7
|
+
/** Load a BrickApp through Vite's server module graph, including dependency HMR. */
|
|
8
|
+
function brickClient(options) {
|
|
9
|
+
const virtualId = "virtual:brick-app";
|
|
10
|
+
const resolvedId = "\0" + virtualId;
|
|
11
|
+
let entry;
|
|
12
|
+
let output;
|
|
13
|
+
let config;
|
|
14
|
+
let buildGeneration;
|
|
15
|
+
let runner;
|
|
16
|
+
let reload = Promise.resolve();
|
|
17
|
+
const dependencies = /* @__PURE__ */ new Set();
|
|
18
|
+
async function writeContract(value) {
|
|
19
|
+
if (!value || typeof value.endpoint !== "function" || !value.definition) throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
20
|
+
const source = generateClientContract(value);
|
|
21
|
+
if (await readFile(output, "utf8").catch((error) => {
|
|
22
|
+
if (error.code !== "ENOENT") throw error;
|
|
23
|
+
}) === source) return;
|
|
24
|
+
await mkdir(dirname(output), { recursive: true });
|
|
25
|
+
await writeFile(output, source);
|
|
26
|
+
}
|
|
27
|
+
function collectDependencies(node, seen = /* @__PURE__ */ new Set()) {
|
|
28
|
+
if (!node || seen.has(node)) return;
|
|
29
|
+
seen.add(node);
|
|
30
|
+
if (node.file) dependencies.add(node.file);
|
|
31
|
+
for (const imported of node.importedModules) collectDependencies(imported, seen);
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
name: "brick:client",
|
|
35
|
+
enforce: "pre",
|
|
36
|
+
configResolved(resolved) {
|
|
37
|
+
config = resolved;
|
|
38
|
+
entry = normalizePath(resolve(config.root, options.entry));
|
|
39
|
+
output = normalizePath(resolve(config.root, options.output ?? "_brick/contract.ts"));
|
|
40
|
+
if (entry === output) throw new Error("Brick: contract output must not overwrite the app entry.");
|
|
41
|
+
},
|
|
42
|
+
async configureServer(server) {
|
|
43
|
+
const environment = server.environments.ssr;
|
|
44
|
+
if (!environment) throw new Error("Brick: client generation requires a Vite SSR environment.");
|
|
45
|
+
runner = new ModuleRunner({
|
|
46
|
+
hmr: false,
|
|
47
|
+
transport: { invoke: (payload) => environment.hot.handleInvoke(payload) }
|
|
48
|
+
});
|
|
49
|
+
await writeContract((await runner.import(entry)).default);
|
|
50
|
+
dependencies.clear();
|
|
51
|
+
collectDependencies(environment.moduleGraph.getModuleById(entry));
|
|
52
|
+
dependencies.add(entry);
|
|
53
|
+
},
|
|
54
|
+
async hotUpdate(context) {
|
|
55
|
+
if (this.environment.name !== "ssr" || !dependencies.has(context.file) || context.file === output) return;
|
|
56
|
+
if (!runner) return;
|
|
57
|
+
const currentRunner = runner;
|
|
58
|
+
reload = reload.catch(() => {}).then(async () => {
|
|
59
|
+
for (const module of context.modules) this.environment.moduleGraph.invalidateModule(module);
|
|
60
|
+
currentRunner.clearCache();
|
|
61
|
+
await writeContract((await currentRunner.import(entry)).default);
|
|
62
|
+
dependencies.clear();
|
|
63
|
+
collectDependencies(this.environment.moduleGraph.getModuleById(entry));
|
|
64
|
+
dependencies.add(entry);
|
|
65
|
+
});
|
|
66
|
+
await reload;
|
|
67
|
+
},
|
|
68
|
+
async closeBundle() {
|
|
69
|
+
await runner?.close();
|
|
70
|
+
},
|
|
71
|
+
async buildStart() {
|
|
72
|
+
if (config.command !== "build") return;
|
|
73
|
+
buildGeneration ??= (async () => {
|
|
74
|
+
const loader = await createServer({
|
|
75
|
+
configFile: false,
|
|
76
|
+
root: config.root,
|
|
77
|
+
mode: config.mode,
|
|
78
|
+
envDir: config.envDir,
|
|
79
|
+
base: config.base,
|
|
80
|
+
define: config.define,
|
|
81
|
+
logLevel: "silent",
|
|
82
|
+
resolve: { alias: config.resolve.alias },
|
|
83
|
+
ssr: config.ssr,
|
|
84
|
+
server: {
|
|
85
|
+
middlewareMode: true,
|
|
86
|
+
watch: null
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
try {
|
|
90
|
+
const environment = loader.environments.ssr;
|
|
91
|
+
if (!environment || !isRunnableDevEnvironment(environment)) throw new Error("Brick: missing build-time SSR loader.");
|
|
92
|
+
await writeContract((await environment.runner.import(entry)).default);
|
|
93
|
+
} finally {
|
|
94
|
+
await loader.close();
|
|
95
|
+
}
|
|
96
|
+
})();
|
|
97
|
+
await buildGeneration;
|
|
98
|
+
},
|
|
99
|
+
resolveId(id) {
|
|
100
|
+
if (id !== virtualId) return;
|
|
101
|
+
if (this.environment.config.consumer === "client") throw new Error("Brick: virtual:brick-app is server-only; never import the backend app in the browser.");
|
|
102
|
+
return resolvedId;
|
|
103
|
+
},
|
|
104
|
+
load(id) {
|
|
105
|
+
if (id !== resolvedId) return;
|
|
106
|
+
return `import app from ${JSON.stringify(entry)};
|
|
107
|
+
if (!app || typeof app.fetch !== "function" || typeof app.endpoint !== "function") {
|
|
108
|
+
throw new Error("Brick: the entry module must default-export a BrickApp created by brick().");
|
|
109
|
+
}
|
|
110
|
+
export default app;
|
|
111
|
+
`;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
export { brickClient };
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=vite.js.map
|
package/dist/vite.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["import { resolve, dirname } from \"node:path\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport {\n createServer,\n isRunnableDevEnvironment,\n normalizePath,\n type Plugin,\n type ResolvedConfig,\n type EnvironmentModuleNode,\n} from \"vite\";\nimport { generateClientContract } from \"./client-contract\";\nimport type { BrickApp } from \"./endpoints\";\nimport { ModuleRunner } from \"vite/module-runner\";\n\nexport interface BrickClientPluginOptions {\n /** Any module whose default export is a BrickApp; do not call listen() there. */\n entry: string;\n /** Generated browser contract, relative to the Vite root (default _brick/contract.ts). */\n output?: string;\n}\n\n/** Load a BrickApp through Vite's server module graph, including dependency HMR. */\nexport function brickClient(options: BrickClientPluginOptions): Plugin {\n const virtualId = \"virtual:brick-app\";\n const resolvedId = \"\\0\" + virtualId;\n let entry: string;\n let output: string;\n let config: ResolvedConfig;\n let buildGeneration: Promise<void> | undefined;\n let runner: ModuleRunner | undefined;\n let reload = Promise.resolve();\n const dependencies = new Set<string>();\n\n async function writeContract(value: unknown) {\n if (\n !value ||\n typeof (value as BrickApp).endpoint !== \"function\" ||\n !(value as BrickApp).definition\n ) {\n throw new Error(\n \"Brick: the entry module must default-export a BrickApp created by brick().\",\n );\n }\n const source = generateClientContract(value as BrickApp);\n const previous = await readFile(output, \"utf8\").catch((error) => {\n if (error.code !== \"ENOENT\") throw error;\n return undefined;\n });\n if (previous === source) return;\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, source);\n }\n\n function collectDependencies(\n node: EnvironmentModuleNode | undefined,\n seen = new Set<EnvironmentModuleNode>(),\n ) {\n if (!node || seen.has(node)) return;\n seen.add(node);\n if (node.file) dependencies.add(node.file);\n for (const imported of node.importedModules)\n collectDependencies(imported, seen);\n }\n\n return {\n name: \"brick:client\",\n enforce: \"pre\",\n configResolved(resolved) {\n config = resolved;\n entry = normalizePath(resolve(config.root, options.entry));\n output = normalizePath(\n resolve(config.root, options.output ?? \"_brick/contract.ts\"),\n );\n if (entry === output)\n throw new Error(\n \"Brick: contract output must not overwrite the app entry.\",\n );\n },\n async configureServer(server) {\n const environment = server.environments.ssr;\n if (!environment)\n throw new Error(\n \"Brick: client generation requires a Vite SSR environment.\",\n );\n // Frameworks such as Start own their SSR runner. Use an independent runner\n // on the same transform graph to read app metadata without changing theirs.\n runner = new ModuleRunner({\n hmr: false,\n transport: {\n invoke: (payload) => environment.hot.handleInvoke(payload),\n },\n });\n await writeContract((await runner.import(entry)).default);\n dependencies.clear();\n collectDependencies(environment.moduleGraph.getModuleById(entry));\n dependencies.add(entry);\n },\n async hotUpdate(context) {\n if (\n this.environment.name !== \"ssr\" ||\n !dependencies.has(context.file) ||\n context.file === output\n )\n return;\n if (!runner) return;\n const currentRunner = runner;\n reload = reload\n .catch(() => {})\n .then(async () => {\n for (const module of context.modules)\n this.environment.moduleGraph.invalidateModule(module);\n currentRunner.clearCache();\n await writeContract((await currentRunner.import(entry)).default);\n dependencies.clear();\n collectDependencies(\n this.environment.moduleGraph.getModuleById(entry),\n );\n dependencies.add(entry);\n });\n await reload;\n },\n async closeBundle() {\n await runner?.close();\n },\n async buildStart() {\n if (config.command !== \"build\") return;\n buildGeneration ??= (async () => {\n // Evaluate the server entry through Vite's TS/alias resolver before client compilation.\n // This loader has no app plugins, so it cannot recursively trigger generation.\n const loader = await createServer({\n configFile: false,\n root: config.root,\n mode: config.mode,\n envDir: config.envDir,\n base: config.base,\n define: config.define,\n logLevel: \"silent\",\n resolve: { alias: config.resolve.alias },\n ssr: config.ssr,\n server: { middlewareMode: true, watch: null },\n });\n try {\n const environment = loader.environments.ssr;\n if (!environment || !isRunnableDevEnvironment(environment))\n throw new Error(\"Brick: missing build-time SSR loader.\");\n await writeContract((await environment.runner.import(entry)).default);\n } finally {\n await loader.close();\n }\n })();\n await buildGeneration;\n },\n resolveId(id) {\n if (id !== virtualId) return;\n if (this.environment.config.consumer === \"client\") {\n throw new Error(\n \"Brick: virtual:brick-app is server-only; never import the backend app in the browser.\",\n );\n }\n return resolvedId;\n },\n load(id) {\n if (id !== resolvedId) return;\n return `import app from ${JSON.stringify(entry)};\nif (!app || typeof app.fetch !== \"function\" || typeof app.endpoint !== \"function\") {\n throw new Error(\"Brick: the entry module must default-export a BrickApp created by brick().\");\n}\nexport default app;\n`;\n },\n };\n}\n"],"mappings":";;;;;;;AAsBA,SAAgB,YAAY,SAA2C;CACrE,MAAM,YAAY;CAClB,MAAM,aAAa,OAAO;CAC1B,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,QAAQ,QAAQ;CAC7B,MAAM,+BAAe,IAAI,IAAY;CAErC,eAAe,cAAc,OAAgB;EAC3C,IACE,CAAC,SACD,OAAQ,MAAmB,aAAa,cACxC,CAAE,MAAmB,YAErB,MAAM,IAAI,MACR,4EACF;EAEF,MAAM,SAAS,uBAAuB,KAAiB;EAKvD,IAAI,MAJmB,SAAS,QAAQ,MAAM,CAAC,CAAC,OAAO,UAAU;GAC/D,IAAI,MAAM,SAAS,UAAU,MAAM;EAErC,CAAC,MACgB,QAAQ;EACzB,MAAM,MAAM,QAAQ,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;EAChD,MAAM,UAAU,QAAQ,MAAM;CAChC;CAEA,SAAS,oBACP,MACA,uBAAO,IAAI,IAA2B,GACtC;EACA,IAAI,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG;EAC7B,KAAK,IAAI,IAAI;EACb,IAAI,KAAK,MAAM,aAAa,IAAI,KAAK,IAAI;EACzC,KAAK,MAAM,YAAY,KAAK,iBAC1B,oBAAoB,UAAU,IAAI;CACtC;CAEA,OAAO;EACL,MAAM;EACN,SAAS;EACT,eAAe,UAAU;GACvB,SAAS;GACT,QAAQ,cAAc,QAAQ,OAAO,MAAM,QAAQ,KAAK,CAAC;GACzD,SAAS,cACP,QAAQ,OAAO,MAAM,QAAQ,UAAU,oBAAoB,CAC7D;GACA,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,0DACF;EACJ;EACA,MAAM,gBAAgB,QAAQ;GAC5B,MAAM,cAAc,OAAO,aAAa;GACxC,IAAI,CAAC,aACH,MAAM,IAAI,MACR,2DACF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AAuC;KACzD,MAAM,eAAe,MAAM,YAAY,OAAO,OAAO,KAAK,EAAA,CAAG,OAAO;IACtE,UAAU;KACR,MAAM,OAAO,MAAM;IACrB;GACF,EAAA,CAAG;GACH,MAAM;EACR;EACA,UAAU,IAAI;GACZ,IAAI,OAAO,WAAW;GACtB,IAAI,KAAK,YAAY,OAAO,aAAa,UACvC,MAAM,IAAI,MACR,uFACF;GAEF,OAAO;EACT;EACA,KAAK,IAAI;GACP,IAAI,OAAO,YAAY;GACvB,OAAO,mBAAmB,KAAK,UAAU,KAAK,EAAE;;;;;;EAMlD;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brickkit/cli",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "CLI and server engine for Brick-TS",
|
|
5
|
+
"license": "MIT",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"main": "./dist/index.js",
|
|
7
8
|
"module": "./dist/index.js",
|
|
@@ -17,13 +18,21 @@
|
|
|
17
18
|
"./compiler": {
|
|
18
19
|
"import": "./dist/compiler.js",
|
|
19
20
|
"types": "./dist/compiler.d.ts"
|
|
21
|
+
},
|
|
22
|
+
"./vite": {
|
|
23
|
+
"import": "./dist/vite.js",
|
|
24
|
+
"types": "./dist/vite.d.ts"
|
|
25
|
+
},
|
|
26
|
+
"./vite/client": {
|
|
27
|
+
"types": "./vite-client.d.ts"
|
|
20
28
|
}
|
|
21
29
|
},
|
|
22
30
|
"publishConfig": {
|
|
23
31
|
"access": "public"
|
|
24
32
|
},
|
|
25
33
|
"files": [
|
|
26
|
-
"dist"
|
|
34
|
+
"dist",
|
|
35
|
+
"vite-client.d.ts"
|
|
27
36
|
],
|
|
28
37
|
"repository": {
|
|
29
38
|
"type": "git",
|
|
@@ -40,15 +49,24 @@
|
|
|
40
49
|
"format:check": "oxfmt --check ."
|
|
41
50
|
},
|
|
42
51
|
"dependencies": {
|
|
43
|
-
"@brickkit/core": "^0.2.
|
|
52
|
+
"@brickkit/core": "^0.2.2",
|
|
44
53
|
"@sinclair/typebox": "^0.34.0",
|
|
45
54
|
"elysia": "^1.2.0"
|
|
46
55
|
},
|
|
47
56
|
"devDependencies": {
|
|
48
57
|
"@types/bun": "latest",
|
|
58
|
+
"oxfmt": "^0.72.0",
|
|
59
|
+
"oxlint": "^1.87.0",
|
|
49
60
|
"tsdown": "^0.23.0",
|
|
50
61
|
"typescript": "^5.7.0",
|
|
51
|
-
"
|
|
52
|
-
|
|
62
|
+
"vite": "^8.3.0"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"vite": "^8.0.0"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"vite": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
53
71
|
}
|
|
54
72
|
}
|
package/vite-client.d.ts
ADDED
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/contract.ts"],"sourcesContent":["import {\n getGlobalRegistry,\n type Action,\n type Resource,\n type Service,\n} from \"@brickkit/core\";\nimport { brick, type CreateServerOptions } from \"./server\";\nimport type { BrickApp } from \"./endpoints\";\n\n/**\n * Options for {@link brickFromContract}: everything `brick()` accepts except\n * `services`, which is derived from the contract itself.\n */\nexport type BrickFromContractOptions = Omit<CreateServerOptions, \"services\">;\n\nfunction isAction(value: unknown): value is Action<any, any, any, any> {\n return (\n typeof value === \"function\" &&\n !!(value as any).config &&\n typeof (value as any).config.execute === \"function\"\n );\n}\n\nfunction isService(value: unknown): value is Service<any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as any).listActions === \"function\" &&\n (value as any).actions instanceof Map\n );\n}\n\nfunction isResource(value: unknown): value is Resource<any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n !isService(value) &&\n !!(value as any).actions &&\n typeof (value as any).actions === \"object\"\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\") return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/** Collects definitions to resolve services; each service registers its own HTTP actions. */\nfunction collectActions(\n node: unknown,\n out: Action<any, any, any, any>[],\n): void {\n if (isAction(node)) {\n out.push(node);\n return;\n }\n if (isService(node)) {\n out.push(...node.listActions(), ...(node.listTools?.() ?? []));\n return;\n }\n if (isResource(node)) {\n out.push(...Object.values(node.actions));\n return;\n }\n if (isPlainObject(node)) {\n for (const value of Object.values(node)) collectActions(value, out);\n }\n}\n\n/**\n * Contract-first server: builds the `brick()` app from the same contract\n * object that types the frontend client, so services are declared once.\n *\n * ```ts\n * // server.ts (backend, single source of truth)\n * export const contract = defineAppContract({\n * page: { list: listPages, create: createPage },\n * billing: { charge: chargeAction },\n * });\n * export type AppServer = typeof contract;\n *\n * export const app = brickFromContract(contract, { port: 4000 });\n * ```\n *\n * ```ts\n * // frontend (type-only import, erased at build)\n * import type { AppServer } from \"./server\";\n * const api = createBrickClient<AppServer>({ baseUrl: \"http://localhost:4000\" });\n * ```\n *\n * Services are resolved through the global registry by each action's\n * `serviceName`, so every definition in the contract must be bound to a service\n * (via `service.action(...)` or `service.tool(...)`). Only HTTP actions\n * registered on that service produce routes. An\n * error names the offending action when it is unbound or its service was\n * never registered.\n */\nexport function brickFromContract<TContract extends Record<string, any>>(\n contract: TContract,\n options: BrickFromContractOptions = {},\n): BrickApp {\n if (!contract || typeof contract !== \"object\") {\n throw new Error(\n \"[Brick-TS] brickFromContract: `contract` must be an object of actions, resources, or services.\",\n );\n }\n\n const actions: Action<any, any, any, any>[] = [];\n collectActions(contract, actions);\n if (actions.length === 0) {\n throw new Error(\n \"[Brick-TS] brickFromContract: contract contains no actions.\",\n );\n }\n\n const unbound = actions.filter((action) => !action.serviceName);\n if (unbound.length > 0) {\n throw new Error(\n `[Brick-TS] brickFromContract: actions not bound to a service (define them via service.action(...)): ${unbound.map((action) => `'${action.name}'`).join(\", \")}.`,\n );\n }\n\n const services: Service<any, any>[] = [];\n const seen = new Set<string>();\n for (const action of actions) {\n const name = action.serviceName!;\n if (seen.has(name)) continue;\n seen.add(name);\n const service = getGlobalRegistry().get(name);\n if (!service) {\n throw new Error(\n `[Brick-TS] brickFromContract: service '${name}' (used by action '${action.name}') is not registered.`,\n );\n }\n services.push(service);\n }\n\n return brick({ ...options, services });\n}\n"],"mappings":";;;;AAeA,SAAS,SAAS,OAAqD;CACrE,OACE,OAAO,UAAU,cACjB,CAAC,CAAE,MAAc,UACjB,OAAQ,MAAc,OAAO,YAAY;AAE7C;AAEA,SAAS,UAAU,OAA4C;CAC7D,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,OAAQ,MAAc,gBAAgB,cACrC,MAAc,mBAAmB;AAEtC;AAEA,SAAS,WAAW,OAA6C;CAC/D,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,CAAC,UAAU,KAAK,KAChB,CAAC,CAAE,MAAc,WACjB,OAAQ,MAAc,YAAY;AAEtC;AAEA,SAAS,cAAc,OAAkD;CACvE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU;AACjD;;AAGA,SAAS,eACP,MACA,KACM;CACN,IAAI,SAAS,IAAI,GAAG;EAClB,IAAI,KAAK,IAAI;EACb;CACF;CACA,IAAI,UAAU,IAAI,GAAG;EACnB,IAAI,KAAK,GAAG,KAAK,YAAY,GAAG,GAAI,KAAK,YAAY,KAAK,CAAC,CAAE;EAC7D;CACF;CACA,IAAI,WAAW,IAAI,GAAG;EACpB,IAAI,KAAK,GAAG,OAAO,OAAO,KAAK,OAAO,CAAC;EACvC;CACF;CACA,IAAI,cAAc,IAAI,GACpB,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,GAAG,eAAe,OAAO,GAA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