brumate 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/check.d.ts +3 -3
  2. package/dist/{boot-DkbcqdUz.d.ts → boot-Cs_P8cDu.d.ts} +2 -2
  3. package/dist/cli.js +77 -6
  4. package/dist/cli.js.map +1 -1
  5. package/dist/{client-CqGDbWd_.d.ts → client-BDPsTd4q.d.ts} +40 -14
  6. package/dist/{client-C3vRNuLi.js → client-DYIZ7BYK.js} +271 -112
  7. package/dist/client-DYIZ7BYK.js.map +1 -0
  8. package/dist/{client-routes-BtGpYCef.js → client-routes-BmPvNr4s.js} +10 -1
  9. package/dist/client-routes-BmPvNr4s.js.map +1 -0
  10. package/dist/{context-btHuB01Z.d.ts → context-BNgBXVUQ.d.ts} +7 -5
  11. package/dist/{context-CTiSzQRc.js → context-CU4Fpn5a.js} +10 -13
  12. package/dist/context-CU4Fpn5a.js.map +1 -0
  13. package/dist/{defer-M18UKyfG.js → defer-7JDhFxQq.js} +2 -2
  14. package/dist/{defer-M18UKyfG.js.map → defer-7JDhFxQq.js.map} +1 -1
  15. package/dist/{devtools-D9Q7a41M.js → devtools-CzSp1GGq.js} +4 -4
  16. package/dist/{devtools-D9Q7a41M.js.map → devtools-CzSp1GGq.js.map} +1 -1
  17. package/dist/{devtools-panel-DTQtljeA.js → devtools-panel-DugGrz7L.js} +32 -9
  18. package/dist/devtools-panel-DugGrz7L.js.map +1 -0
  19. package/dist/{features-CbgII-o7.js → features-DwMYKBIC.js} +6 -2
  20. package/dist/features-DwMYKBIC.js.map +1 -0
  21. package/dist/{files-DtDH5AR4.js → files-XX5yW3KL.js} +94 -3
  22. package/dist/files-XX5yW3KL.js.map +1 -0
  23. package/dist/index.d.ts +44 -0
  24. package/dist/index.js +3 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/{inspect-Bonq6EJO.js → inspect-B9cRF6AM.js} +2670 -2074
  27. package/dist/inspect-B9cRF6AM.js.map +1 -0
  28. package/dist/{loader-C-S3yzep.js → loader-BGSXt_Eb.js} +5 -5
  29. package/dist/{loader-C-S3yzep.js.map → loader-BGSXt_Eb.js.map} +1 -1
  30. package/dist/{rpc-C_znDZ_w.js → rpc-B9EkaPdU.js} +3 -3
  31. package/dist/{rpc-C_znDZ_w.js.map → rpc-B9EkaPdU.js.map} +1 -1
  32. package/dist/runtime/bundles.d.ts +1 -1
  33. package/dist/runtime/bundles.js +2 -0
  34. package/dist/runtime/bundles.js.map +1 -1
  35. package/dist/runtime/client.d.ts +4 -4
  36. package/dist/runtime/client.js +4 -4
  37. package/dist/runtime/context.d.ts +2 -2
  38. package/dist/runtime/context.js +1 -1
  39. package/dist/runtime/devtools.d.ts +2 -2
  40. package/dist/runtime/devtools.js +1 -1
  41. package/dist/runtime/hot.d.ts +1 -1
  42. package/dist/runtime/html.d.ts +1 -1
  43. package/dist/runtime/loader.d.ts +2 -2
  44. package/dist/runtime/loader.js +2 -2
  45. package/dist/runtime/server.d.ts +4 -4
  46. package/dist/runtime/server.js +4 -4
  47. package/dist/runtime/signals.d.ts +2 -2
  48. package/dist/runtime/signals.js +43 -5
  49. package/dist/runtime/signals.js.map +1 -1
  50. package/dist/runtime/static-loader.d.ts +2 -2
  51. package/dist/runtime/static-loader.js +1 -1
  52. package/dist/runtime/store.d.ts +2 -0
  53. package/dist/runtime/store.js +1 -0
  54. package/dist/runtime/testing.d.ts +2 -2
  55. package/dist/runtime/testing.js +2 -2
  56. package/dist/{search-params-CM1RWR2P.js → search-params-Cy3uRphR.js} +33 -8
  57. package/dist/search-params-Cy3uRphR.js.map +1 -0
  58. package/dist/{server-BcT9icQ4.js → server-C1OTFH4r.js} +127 -14
  59. package/dist/server-C1OTFH4r.js.map +1 -0
  60. package/dist/{server-dP_ucRiJ.d.ts → server-CavhuoFI.d.ts} +32 -8
  61. package/dist/{shared-CzbnWkVA.d.ts → shared-CRduzyi3.d.ts} +15 -2
  62. package/dist/{signals-BwD4u22K.d.ts → signals-DBnq9QRW.d.ts} +46 -6
  63. package/dist/{static-loader-DysAET-w.d.ts → static-loader-D5hvLQK7.d.ts} +2 -2
  64. package/dist/{static-loader-Bt2WDkY1.js → static-loader-XGXMzfJR.js} +3 -3
  65. package/dist/{static-loader-Bt2WDkY1.js.map → static-loader-XGXMzfJR.js.map} +1 -1
  66. package/dist/store-BIBAYZo-.js +293 -0
  67. package/dist/store-BIBAYZo-.js.map +1 -0
  68. package/dist/store-xlTzAM_r.d.ts +171 -0
  69. package/dist/{stream-DRjx0keF.js → stream-BBnArf_5.js} +89 -3
  70. package/dist/stream-BBnArf_5.js.map +1 -0
  71. package/dist/vite.d.ts +1 -1
  72. package/dist/vite.js +128 -13
  73. package/dist/vite.js.map +1 -1
  74. package/elements.d.ts +268 -21
  75. package/package.json +5 -1
  76. package/skills/brumate/SKILL.md +1 -1
  77. package/skills/brumate/references/errors.md +127 -9
  78. package/skills/brumate/references/signals.md +37 -30
  79. package/skills/brumate/references/state.md +3 -2
  80. package/dist/client-C3vRNuLi.js.map +0 -1
  81. package/dist/client-routes-BtGpYCef.js.map +0 -1
  82. package/dist/context-CTiSzQRc.js.map +0 -1
  83. package/dist/devtools-panel-DTQtljeA.js.map +0 -1
  84. package/dist/features-CbgII-o7.js.map +0 -1
  85. package/dist/files-DtDH5AR4.js.map +0 -1
  86. package/dist/inspect-Bonq6EJO.js.map +0 -1
  87. package/dist/search-params-CM1RWR2P.js.map +0 -1
  88. package/dist/server-BcT9icQ4.js.map +0 -1
  89. package/dist/stream-DRjx0keF.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-BBnArf_5.js","names":[],"sources":["../src/runtime/calls.ts","../src/runtime/serial.ts","../src/runtime/stream.ts"],"sourcesContent":["// Values that only server function calls and their serialization use. They are\n// not in `shared.ts`, which the core imports, so a page's core does not hold them.\n\nimport type { FunctionReference } from './shared.ts';\n\n/**\n * Client functions that the server passes on, such as function props, with\n * their references. Kept under a symbol of the registry, so two copies of the\n * runtime, such as a component's and the render context's, share it.\n */\nexport const functionReferences: WeakMap<object, FunctionReference> = ((\n globalThis as Record<symbol, WeakMap<object, FunctionReference> | undefined>\n)[Symbol.for('brumate.functionReferences')] ??= new WeakMap());\n\n/**\n * True for a file or a blob. One from another frame, or another DOM, is an\n * instance of another `Blob` class, so its methods tell instead.\n */\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n return true;\n }\n const blob = value as Partial<Blob> | null;\n return (\n typeof blob === 'object' &&\n blob !== null &&\n typeof blob.size === 'number' &&\n typeof blob.type === 'string' &&\n typeof blob.arrayBuffer === 'function' &&\n typeof blob.slice === 'function'\n );\n}\n","// The seroval plugins of brumate's values. The server writes the page state\n// with them as code, and server function calls as JSON, which both sides\n// read with them. The core does not import this module: a state record\n// is code that makes its values with `stateValues`, so seroval loads in the\n// browser only with the first server function call.\n\nimport { Feature, createPlugin } from 'seroval';\nimport {\n AbortSignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n RequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n} from 'seroval-plugins/web';\nimport type {\n Plugin,\n SerovalNode,\n StreamParsePluginContext,\n SyncParsePluginContext,\n} from 'seroval';\nimport { type Internal, isInternal, isRaw, rawHTML } from './html.ts';\nimport type { Raw } from './html.ts';\nimport { functionReferences, isBlob } from './calls.ts';\nimport { MODIFIERS } from './events.ts';\nimport { HAS_BRIDGES } from './features.ts';\nimport {\n CHILDREN_REF,\n ElementReference,\n PARTS,\n isBinding,\n isPropWrapper,\n isSlotReference,\n onSerialOptions,\n onValuePlugin,\n stateValues,\n} from './shared.ts';\nimport type { ChildrenReference, MemoError, PropPromise, ScopeId } from './shared.ts';\nimport type { ValuePlugin } from './values.ts';\nimport { isBridged, isStore } from './store.ts';\nimport type { Bridged, Store } from './store.ts';\nimport type { Binding, SlotReference } from './shared.ts';\nimport type { ComponentValue } from './shared.ts';\n\ntype ReferenceNode = { a: SerovalNode; b: SerovalNode; c?: SerovalNode; d?: SerovalNode };\n\n/** Serializes the parts of a node that are set, joined as call arguments. */\nfunction serializeParts(\n parts: (SerovalNode | undefined)[],\n ctx: { serialize(node: SerovalNode): string },\n): string {\n const written: string[] = [];\n for (const part of parts) {\n if (part !== undefined) {\n written.push(ctx.serialize(part));\n }\n }\n return written.join(',');\n}\n\n/**\n * Returns the parse functions of a plugin. `read` returns the values of the\n * node by key, and each mode parses them in that order, so the nodes match.\n */\nfunction parsers<T, K extends string>(\n read: (value: T) => Record<K, unknown>,\n): Plugin<T, Record<K, SerovalNode>>['parse'] {\n type N = Record<K, SerovalNode>;\n function parse(value: T, ctx: SyncParsePluginContext | StreamParsePluginContext): N {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n node[key] = ctx.parse(node[key]);\n }\n return node as N;\n }\n return {\n sync: parse,\n stream: parse,\n async: async (value, ctx) => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n // oxlint-disable-next-line no-await-in-loop -- In order, as the other modes parse, so the IDs match.\n node[key] = await ctx.parse(node[key]);\n }\n return node as N;\n },\n };\n}\n\n// In the page state, each value is a call of `stateValues`, which the code of a record gets as `$b`.\n\n// No plugin here matches a plain object, so each one sets skipPlainObjects and seroval\n// does not run its test on object literals. Raw HTML is a class instance for this reason.\nconst ElementPlugin = createPlugin<ElementReference, ReferenceNode>({\n tag: 'brumate/element',\n skipPlainObjects: true,\n test: (value) => value instanceof ElementReference,\n parse: parsers((value) => ({ a: value.scope, b: value.anchor })),\n serialize: (node, ctx) => `$b.e(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.e(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\nconst SlotPlugin = createPlugin<SlotReference, ReferenceNode>({\n tag: 'brumate/slot',\n skipPlainObjects: true,\n test: (value) => isSlotReference(value),\n parse: parsers((value) => ({ a: value.scope, b: value.slot })),\n serialize: (node, ctx) => `$b.l(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.l(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\n/** A binding that a rest prop holds: its value, and the scope and the slot it writes. */\nconst BindingPlugin = createPlugin<Binding, ReferenceNode>({\n tag: 'brumate/binding',\n skipPlainObjects: true,\n test: (value) => isBinding(value),\n parse: parsers((value) => {\n const node: Record<string, unknown> = { a: value.value, b: value.ref.scope, c: value.ref.slot };\n // The setter of `$bind(name, fn)`.\n if (value.set !== undefined) {\n node.d = value.set;\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) => `$b.b(${serializeParts([node.a, node.b, node.c, node.d], ctx)})`,\n deserialize: (node, ctx) =>\n stateValues.b(\n ctx.deserialize(node.a),\n ctx.deserialize<number>(node.b!),\n ctx.deserialize<number>(node.c!),\n node.d === undefined ? undefined : ctx.deserialize(node.d),\n ),\n});\n\nconst FunctionPlugin = createPlugin<object, ReferenceNode>({\n tag: 'brumate/function',\n skipPlainObjects: true,\n test: (value) => typeof value === 'function' && functionReferences.has(value),\n parse: parsers((value) => {\n const reference = functionReferences.get(value)!;\n // The arguments of a handler that `$handler` made go with it.\n const node: Record<string, unknown> = { a: reference.ref, b: reference.scope };\n // The modifiers of its wrappers, so a spread in markup that the browser renders writes them.\n const modifiers = (value as { [MODIFIERS]?: string[] })[MODIFIERS];\n if (reference.args !== undefined || modifiers) {\n node.c = reference.args ?? null;\n }\n if (modifiers) {\n node.d = modifiers;\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) => `$b.f(${serializeParts([node.a, node.b, node.c, node.d], ctx)})`,\n deserialize: (node, ctx) =>\n stateValues.f(\n ctx.deserialize<string>(node.a),\n ctx.deserialize<number>(node.b),\n node.c === undefined ? undefined : ctx.deserialize<unknown[] | null>(node.c),\n node.d === undefined ? undefined : ctx.deserialize<string[]>(node.d),\n ),\n});\n\n/** A handler that merges the handlers of one event, as the parts that refer to client functions. */\nconst MergedPlugin = createPlugin<object, { a: SerovalNode }>({\n tag: 'brumate/merged',\n skipPlainObjects: true,\n test: (value) => typeof value === 'function' && PARTS in value,\n parse: parsers((value) => {\n const parts: object[] = [];\n for (const part of (value as { [PARTS]: object[] })[PARTS]) {\n if (functionReferences.has(part)) {\n parts.push(part);\n }\n }\n return { a: parts };\n }),\n serialize: (node, ctx) => `$b.m(${ctx.serialize(node.a)})`,\n deserialize: (node, ctx) => stateValues.m(ctx.deserialize(node.a)),\n});\n\n/**\n * A value of an attribute that brumate writes, which a live rest prop can hold. The ones that\n * reach the page state are the scoped style attribute and `b-v`. The error \"holds a Internal\"\n * no longer catches any other, so a new one needs a check of its own.\n */\nconst InternalPlugin = createPlugin<Internal, { a: SerovalNode }>({\n tag: 'brumate/internal',\n skipPlainObjects: true,\n test: (value) => isInternal(value),\n parse: parsers((value) => ({ a: value.value })),\n serialize: (node, ctx) => `$b.i(${ctx.serialize(node.a)})`,\n deserialize: (node, ctx) => stateValues.i(ctx.deserialize(node.a)),\n});\n\n/** Children of a component, as the export that renders them in the browser. */\nconst ChildrenPlugin = createPlugin<object, ReferenceNode>({\n tag: 'brumate/children',\n skipPlainObjects: true,\n test: (value) => typeof value === 'object' && value !== null && CHILDREN_REF in value,\n parse: parsers((value) => {\n const reference = (value as { [CHILDREN_REF]: ChildrenReference })[CHILDREN_REF];\n const node: Record<string, unknown> = { a: reference.ref, b: reference.scope };\n // The scope and the anchor of the insert where the server rendered them.\n if (reference.at !== undefined) {\n node.c = reference.at;\n node.d = reference.anchor;\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) => `$b.n(${serializeParts([node.a, node.b, node.c, node.d], ctx)})`,\n deserialize: (node, ctx) =>\n stateValues.n(\n ctx.deserialize<string>(node.a),\n ctx.deserialize<ScopeId>(node.b!),\n node.c === undefined ? undefined : ctx.deserialize<ScopeId>(node.c),\n node.d === undefined ? undefined : ctx.deserialize<number>(node.d),\n ),\n});\n\n/**\n * A memo that failed on the server. The page state holds its error, so a read in the browser\n * throws it, as a memo that failed there. The server writes the error that is safe to send. See\n * `stateValue`.\n */\nconst MemoErrorPlugin = createPlugin<MemoError, { e: SerovalNode }>({\n tag: 'brumate/memo-error',\n skipPlainObjects: true,\n // The server marks the errors it holds, so the copies of the runtime agree on them.\n test: (value) =>\n typeof value === 'object' && value !== null && Symbol.for('brumate.held') in value,\n parse: parsers((value) => ({ e: value.error })),\n serialize: (node, ctx) => `$b.x(${ctx.serialize(node.e)})`,\n deserialize: (node, ctx) => stateValues.x(ctx.deserialize(node.e)),\n});\n\n/** A promise prop in the page state. See `PropPromise`. */\nconst PropPromisePlugin = createPlugin<PropPromise, { p: SerovalNode }>({\n tag: 'brumate/prop-promise',\n skipPlainObjects: true,\n test: isPropWrapper,\n parse: parsers((value) => ({ p: value.promise })),\n serialize: (node, ctx) => `$b.q(${ctx.serialize(node.p)})`,\n deserialize: (node, ctx) => stateValues.q(ctx.deserialize(node.p)),\n});\n\n/** HTML, such as the `children` of a component, so the client can insert it again. */\nconst RawPlugin = createPlugin<Raw, { h: SerovalNode }>({\n tag: 'brumate/raw',\n skipPlainObjects: true,\n test: isRaw,\n parse: parsers((value) => ({ h: rawHTML(value) })),\n serialize: (node, ctx) => `$b.r(${ctx.serialize(node.h)})`,\n deserialize: (node, ctx) => stateValues.r(ctx.deserialize<string>(node.h)),\n});\n\n/** A component in the page state, such as the value of a dynamic tag. See `stateValues.c`. */\nconst ComponentPlugin = createPlugin<ComponentValue, { c: SerovalNode }>({\n tag: 'brumate/component',\n skipPlainObjects: true,\n test: (value) =>\n typeof value === 'function' && typeof (value as Partial<ComponentValue>).brumateId === 'string',\n parse: parsers((value) => ({ c: value.brumateId })),\n serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,\n deserialize: (node, ctx) => stateValues.c(ctx.deserialize<string>(node.c)),\n});\n\n/**\n * A store of `brumate/store`: only its value crosses, and where `$toStore` made it, so the\n * browser makes a new store that the provider writes. Readers subscribe as their scopes resume.\n */\nconst StorePlugin = createPlugin<Store<unknown>, ReferenceNode>({\n tag: 'brumate/store',\n skipPlainObjects: true,\n test: isStore,\n parse: parsers((value) => {\n const node: Record<string, unknown> = { a: value.v };\n if (value.o) {\n node.b = value.o[0];\n node.c = value.o[1];\n if (value.o[2] !== undefined) {\n node.d = value.o[2];\n }\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) => `$b.s(${serializeParts([node.a, node.b, node.c, node.d], ctx)})`,\n deserialize: (node, ctx) =>\n stateValues.s(\n ctx.deserialize(node.a),\n node.b === undefined ? undefined : ctx.deserialize<ScopeId>(node.b),\n node.c === undefined ? undefined : ctx.deserialize<number>(node.c),\n node.d === undefined ? undefined : ctx.deserialize<number>(node.d),\n ),\n});\n\n/**\n * The index of a file or a blob, and what a part of multipart form data does\n * not keep: the type (an empty one arrives as `application/octet-stream`),\n * whether the value was a blob or a file (every part arrives as a file), and\n * the name (some characters are escaped) and `lastModified` of a file. Calls\n * from pages before these fields send only the index.\n */\ntype UploadNode = { i: SerovalNode; t?: SerovalNode; n?: SerovalNode; l?: SerovalNode };\n\nfunction isFile(value: Blob): value is File {\n const file = value as Partial<File>;\n return typeof file.name === 'string' && typeof file.lastModified === 'number';\n}\n\n/**\n * Files and blobs, which go only in the arguments of a call, as parts of\n * multipart form data named `file<index>`. The node holds the index. The\n * call passes `sent`, which gets each blob, and the server passes the form\n * that it `received`, whose files the indexes read. Without them, as in the\n * page state and in the answer of a call, a blob throws.\n */\nexport function uploadPlugin(sent?: Blob[], received?: FormData): Plugin<Blob, UploadNode> {\n return createPlugin<Blob, UploadNode>({\n tag: 'brumate/upload',\n skipPlainObjects: true,\n test: isBlob,\n // Only the fields that are set go in the node, so `K` names just the index.\n parse: parsers<Blob, 'i'>((value) => {\n if (!sent) {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n }\n const index = sent.push(value) - 1;\n if (isFile(value)) {\n return { i: index, t: value.type, n: value.name, l: value.lastModified };\n }\n return { i: index, t: value.type };\n }) as Plugin<Blob, UploadNode>['parse'],\n serialize: () => {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n },\n deserialize: (node, ctx) => {\n const file = received?.get(`file${ctx.deserialize<number>(node.i)}`);\n if (!(file instanceof Blob)) {\n throw new TypeError('A file of the call is missing');\n }\n // A page before the metadata fields sends only the index.\n if (node.t === undefined) {\n return file;\n }\n const type = ctx.deserialize(node.t);\n if (typeof type !== 'string') {\n throw new TypeError('A file of the call is malformed');\n }\n // The new blob or file refers to the bytes of the part instead of copying them.\n if (node.n === undefined) {\n return new Blob([file], { type });\n }\n const name = ctx.deserialize(node.n);\n const lastModified = node.l === undefined ? undefined : ctx.deserialize(node.l);\n if (typeof name !== 'string' || typeof lastModified !== 'number') {\n throw new TypeError('A file of the call is malformed');\n }\n return new File([file], name, { type, lastModified });\n },\n });\n}\n\n/**\n * The plugin of `AbortSignal` from seroval-plugins, which sends whether the\n * signal aborted and its reason. The one of seroval-plugins waits for a live\n * signal to abort, so a call with one would not be sent, and a page or an\n * answer with one would not end.\n */\nconst SignalPlugin: typeof AbortSignalPlugin = {\n ...AbortSignalPlugin,\n parse: {\n sync: AbortSignalPlugin.parse.sync,\n stream: AbortSignalPlugin.parse.sync,\n async: async (value, ctx) => (value.aborted ? { reason: await ctx.parse(value.reason) } : {}),\n },\n};\n\n/**\n * The plugin of `Request` from seroval-plugins, whose body streams in the\n * stream mode. A request with a stream body needs `duplex: 'half'`, or its\n * constructor throws, so the plugin adds it.\n */\nconst BodyRequestPlugin: typeof RequestPlugin = {\n ...RequestPlugin,\n serialize: (node, ctx) =>\n `new Request(${ctx.serialize(node.url)},Object.assign(${ctx.serialize(node.options)},{duplex:\"half\"}))`,\n deserialize: (node, ctx) =>\n new Request(\n ctx.deserialize(node.url) as string,\n {\n ...(ctx.deserialize(node.options) as RequestInit),\n duplex: 'half',\n } as RequestInit,\n ),\n};\n\n/**\n * The error of a store of `bridge()` whose data the page state cannot send. It holds the store as\n * `value`, so the server finds the context or the prop that sends it.\n */\nexport class BridgeDataError extends Error {\n value: Bridged<unknown, unknown>;\n\n constructor(value: Bridged<unknown, unknown>, cause: unknown) {\n super(`get of the bridge \"${value.id}\" gives data that cannot be sent`, { cause });\n this.value = value;\n }\n}\n\n/** Reads the data of a bridged store for the page state. */\nfunction bridgeData(value: Bridged<unknown, unknown>): unknown {\n if (value.id === undefined) {\n throw new BridgeDataError(\n value,\n new Error(\n 'The bridge has no name. Keep bridge() in a module-level export of a script file, as \"export const name = bridge({ … })\", so the compiler names it',\n ),\n );\n }\n return value.get();\n}\n\n/** The node of a bridged store: its data and its name. An error of the data names the store. */\nfunction bridgeNode(\n value: Bridged<unknown, unknown>,\n parse: (data: unknown) => SerovalNode,\n): ReferenceNode {\n try {\n return { a: parse(bridgeData(value)), b: parse(value.id), c: parse(value.set ? 1 : 0) };\n } catch (error) {\n throw error instanceof BridgeDataError ? error : new BridgeDataError(value, error);\n }\n}\n\n/**\n * A store of `bridge()`: only the data that `get` reads crosses, and the name of the bridge, so\n * the browser makes the library's store again from the data at the first subscriber.\n */\nfunction makeBridgePlugin(): Plugin<Bridged<unknown, unknown>, ReferenceNode> {\n return createPlugin<Bridged<unknown, unknown>, ReferenceNode>({\n tag: 'brumate/bridge',\n skipPlainObjects: true,\n test: isBridged,\n parse: {\n sync: (value, ctx) => bridgeNode(value, (data) => ctx.parse(data)),\n stream: (value, ctx) => bridgeNode(value, (data) => ctx.parse(data)),\n async: async (value, ctx) => {\n try {\n const data = bridgeData(value);\n return {\n a: await ctx.parse(data),\n b: await ctx.parse(value.id),\n c: await ctx.parse(value.set ? 1 : 0),\n };\n } catch (error) {\n throw error instanceof BridgeDataError ? error : new BridgeDataError(value, error);\n }\n },\n },\n serialize: (node, ctx) =>\n `$b.g(${ctx.serialize(node.a)},${ctx.serialize(node.b)},${ctx.serialize(node.c!)})`,\n deserialize: (node, ctx) =>\n stateValues.g(\n ctx.deserialize(node.a),\n ctx.deserialize<string>(node.b),\n ctx.deserialize<number>(node.c!),\n ),\n });\n}\n\n/** The plugins after the plugin of uploads, which a call makes for its files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nconst valuePlugins: Plugin<any, any>[] = [\n ElementPlugin,\n SlotPlugin,\n BindingPlugin,\n FunctionPlugin,\n MergedPlugin,\n InternalPlugin,\n MemoErrorPlugin,\n PropPromisePlugin,\n ChildrenPlugin,\n RawPlugin,\n ComponentPlugin,\n StorePlugin,\n ...(HAS_BRIDGES ? [makeBridgePlugin()] : []),\n // The web values of seroval-plugins. Requests and responses need the async or stream modes,\n // so a page state or a call result that holds one streams. The plugin of uploads takes files\n // and blobs, so those of seroval-plugins, which would put their bytes in the JSON, are left out.\n SignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n BodyRequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n];\n\n/**\n * The plugins of a call with files: `sent` gets the files that the call\n * sends, and `received` is the form that the server got them in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport function callPlugins(sent?: Blob[], received?: FormData): Plugin<any, any>[] {\n return [uploadPlugin(sent, received), ...valuePlugins];\n}\n\n/** The plugins of the page state, of answers and of calls without files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const plugins: Plugin<any, any>[] = callPlugins();\n\n/**\n * Stops a sync mode at a value that only streams: an async iterable, such\n * as a `ReadableStream`. seroval writes one in a sync mode as a stream that\n * never gets its values, without an error.\n */\nconst StreamGuardPlugin = createPlugin<object, Record<string, never>>({\n tag: 'brumate/stream-guard',\n test: (value) =>\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream) ||\n (typeof value === 'object' && value !== null && Symbol.asyncIterator in value),\n parse: {\n sync: () => {\n throw new Error('A stream needs the async or stream mode');\n },\n },\n serialize: () => '',\n deserialize: () => ({}),\n});\n\n/**\n * The plugins for the sync modes, which must throw for a value that only\n * streams, so the page state streams instead, and a call with a stream in\n * its arguments is not shared with another. The guard comes first, so it\n * takes a `ReadableStream` before the plugin of `ReadableStream`, which the\n * plugins of `Request` and `Response` bring in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const syncPlugins: Plugin<any, any>[] = [StreamGuardPlugin, ...plugins];\n\n/**\n * The seroval plugin of a plugin of the app. The page state writes its value\n * as `$b.u(tag, data)`, so the record does not need the class in scope.\n */\nfunction appPlugin(plugin: ValuePlugin): Plugin<unknown, { d: SerovalNode }> {\n return createPlugin<unknown, { d: SerovalNode }>({\n tag: `app:${plugin.tag}`,\n test: plugin.test,\n parse: parsers((value) => ({ d: plugin.toData(value) })),\n serialize: (node, ctx) => `$b.u(${JSON.stringify(plugin.tag)},${ctx.serialize(node.d)})`,\n deserialize: (node, ctx) => plugin.fromData(ctx.deserialize(node.d)),\n });\n}\n\n// The plugins of the app come before brumate's, in each list, as the entry adds them. The\n// plugin of uploads stays first in a call, and the guard of streams first in the sync modes.\nonValuePlugin((plugin) => {\n const added = appPlugin(plugin);\n valuePlugins.unshift(added);\n plugins.splice(1, 0, added);\n syncPlugins.splice(2, 0, added);\n});\n\n/**\n * Features that are off in both directions:\n *\n * - Errors keep their name and message only. A stack trace would show the\n * server's files and code to the browser.\n * - Regular expressions are not sent. A pattern from a client could take\n * the server a long time to match, and reading one is refused as well.\n */\nconst BRUMATE_DISABLED = Feature.ErrorPrototypeStack | Feature.RegExp;\n\nexport let disabledFeatures: number = BRUMATE_DISABLED;\nlet depthLimit: number | undefined;\n\n/** The options of every call of seroval: the features that are off, and the depth limit of the entry. */\nexport function serialOptions(): { disabledFeatures: number; depthLimit?: number } {\n return depthLimit === undefined ? { disabledFeatures } : { disabledFeatures, depthLimit };\n}\n\nonSerialOptions((options) => {\n disabledFeatures = options.disabledFeatures ?? BRUMATE_DISABLED;\n depthLimit = options.depthLimit;\n // oxlint-disable-next-line no-bitwise -- The features are flags.\n const enabled = BRUMATE_DISABLED & ~disabledFeatures;\n if (enabled !== 0) {\n console.warn(\n `The serial entry turns on ${enabled & Feature.RegExp ? 'RegExp' : 'ErrorPrototypeStack'}, which brumate turns off: ${enabled & Feature.RegExp ? 'a pattern from a client can take the server a long time to match' : 'a stack shows the files and code of the server to the browser'}.`,\n );\n }\n});\n","// The answer of a server function, as a stream of seroval chunks. Promises\n// and async iterables in the answer settle as their chunks arrive.\n//\n// Each chunk is a 12-byte header with the size of its data in bytes, as 8\n// hex digits, and the data: `;0x0000001f;{...}`. The reader knows how many\n// bytes to wait for, and can refuse a chunk that is too large.\n\nimport { Stream, fromCrossJSON, toCrossJSONStream } from 'seroval';\nimport type { SerovalNode } from 'seroval';\nimport { serialOptions, plugins } from './serial.ts';\n\nconst HEADER_SIZE = 12;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** The content type of a stream of chunks. */\nexport const STREAM_TYPE = 'application/x-brumate-stream';\n\n/** One chunk: its header and its data, in one array. */\nfunction chunk(text: string): Uint8Array {\n const data = encoder.encode(text);\n const result = new Uint8Array(HEADER_SIZE + data.length);\n encoder.encodeInto(`;0x${data.length.toString(16).padStart(8, '0')};`, result);\n result.set(data, HEADER_SIZE);\n return result;\n}\n\n/** Serializes a value as a stream of chunks. */\nexport function toChunkStream(\n value: unknown,\n onCancel?: (reason: unknown) => void,\n): ReadableStream<Uint8Array> {\n let cancelled = false;\n return new ReadableStream({\n start(controller) {\n toCrossJSONStream(value, {\n refs: new Map(),\n plugins,\n ...serialOptions(),\n onParse(node) {\n if (!cancelled) {\n controller.enqueue(chunk(JSON.stringify(node)));\n }\n },\n onDone() {\n if (!cancelled) {\n controller.close();\n }\n },\n onError(error) {\n if (!cancelled) {\n controller.error(error);\n }\n },\n });\n },\n // The reader went away, such as a browser that aborted the call.\n cancel(reason) {\n cancelled = true;\n onCancel?.(reason);\n },\n });\n}\n\n/** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */\nclass ChunkReader {\n private readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n private pieces: Uint8Array[] = [];\n private length = 0;\n private done = false;\n\n constructor(stream: ReadableStream<Uint8Array>) {\n this.reader = stream.getReader();\n }\n\n private async fill(size: number): Promise<void> {\n while (this.length < size && !this.done) {\n // oxlint-disable-next-line no-await-in-loop -- Pieces arrive in order.\n const piece = await this.reader.read();\n if (piece.done) {\n this.done = true;\n } else {\n this.pieces.push(piece.value);\n this.length += piece.value.length;\n }\n }\n }\n\n private take(size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n while (offset < size) {\n const piece = this.pieces[0]!;\n const count = Math.min(piece.length, size - offset);\n result.set(piece.subarray(0, count), offset);\n offset += count;\n if (count === piece.length) {\n this.pieces.shift();\n } else {\n this.pieces[0] = piece.subarray(count);\n }\n }\n this.length -= size;\n return result;\n }\n\n /** The data of the next chunk, or undefined at the end of the stream. */\n async next(): Promise<string | undefined> {\n await this.fill(HEADER_SIZE);\n if (this.length === 0) {\n return undefined;\n }\n const head = this.length < HEADER_SIZE ? '' : decoder.decode(this.take(HEADER_SIZE));\n const match = /^;0x([0-9a-f]{8});$/.exec(head);\n if (!match) {\n throw new Error('The answer of a server function is not a stream of chunks');\n }\n const size = Number.parseInt(match[1]!, 16);\n await this.fill(size);\n if (this.length < size) {\n throw new Error('The answer of a server function ended in the middle of a chunk');\n }\n return decoder.decode(this.take(size));\n }\n\n cancel(reason: unknown): void {\n this.done = true;\n void this.reader.cancel(reason).catch(() => {});\n }\n}\n\nfunction ignore(): void {}\n\n/**\n * The refs of a stream. A promise in the answer can fail with nothing that\n * reads it, such as a field the caller ignores, so its failure is claimed\n * here. Code that awaits it still sees the failure.\n */\nclass Refs extends Map<number, unknown> {\n override set(id: number, value: unknown): this {\n if (value instanceof Promise) {\n value.catch(ignore);\n }\n return super.set(id, value);\n }\n}\n\n/**\n * Fails the promises and async iterables that still wait for a chunk, when\n * the stream ends early. Failing a settled one does nothing.\n */\nfunction failPending(refs: Refs, error: unknown): void {\n for (const value of refs.values()) {\n try {\n // The deserializer makes a Stream. A LiveStream comes only from user code, and its producer fails it.\n if (value instanceof Stream) {\n value.throw(error);\n } else if (value !== null && typeof value === 'object') {\n const resolver = value as { p?: unknown; f?: unknown };\n if (resolver.p instanceof Promise && typeof resolver.f === 'function') {\n resolver.p.catch(ignore);\n (resolver.f as (error: unknown) => void)(error);\n }\n }\n } catch {\n // A value that a plugin made, which has no such methods.\n }\n }\n}\n\n/**\n * Reads the first chunk of a stream as the value, and the rest in the\n * background, so the promises and async iterables in it settle as their\n * chunks arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = new ChunkReader(stream);\n const refs = new Refs();\n function read(data: string): unknown {\n return fromCrossJSON(JSON.parse(data) as SerovalNode, { refs, plugins, ...serialOptions() });\n }\n const first = await reader.next();\n if (first === undefined) {\n throw new Error('The answer of a server function is empty');\n }\n const value = read(first);\n void (async () => {\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const data = await reader.next();\n if (data === undefined) {\n break;\n }\n read(data);\n }\n failPending(refs, new Error('The answer of a server function ended early'));\n } catch (error) {\n reader.cancel(error);\n failPending(refs, error);\n }\n })();\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,MAAa,qBAA0D,WAErE,OAAO,IAAI,4BAA4B,uBAAO,IAAI,QAAQ;;;;;AAM5D,SAAgB,OAAO,OAA+B;CACpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAClD,OAAO;CAET,MAAM,OAAO;CACb,OACE,OA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AK;CAChC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,0CAA0C;CAE5D,MAAM,QAAQ,KAAK,KAAK;CACxB,CAAM,YAAY;EAChB,IAAI;GACF,SAAS;IAEP,MAAM,OAAO,MAAM,OAAO,KAAK;IAC/B,IAAI,SAAS,KAAA,GACX;IAEF,KAAK,IAAI;GACX;GACA,YAAY,sBAAM,IAAI,MAAM,6CAA6C,CAAC;EAC5E,SAAS,OAAO;GACd,OAAO,OAAO,KAAK;GACnB,YAAY,MAAM,KAAK;EACzB;CACF,EAAA,CAAG;CACH,OAAO;AACT"}
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as NavigateOptions } from "./boot-DkbcqdUz.js";
1
+ import { n as NavigateOptions } from "./boot-Cs_P8cDu.js";
2
2
  import { Plugin, ViteDevServer } from "vite";
3
3
  //#region src/report.d.ts
4
4
  /** Sizes in bytes, after gzip. */
package/dist/vite.js CHANGED
@@ -1,7 +1,7 @@
1
- import { A as analyzeProject, B as getLocation, C as isReactiveModule, E as originalPosition, I as parse, J as walk, M as importSource, N as importedComponents, O as entryClasses, P as resolveRelative, R as forEachNode, T as builtin, U as analyze, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, q as resolveMacros, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash } from "./inspect-Bonq6EJO.js";
1
+ import { A as analyzeProject, C as isReactiveModule, E as originalPosition, G as bridgeModuleId, H as resolveMacros, I as parse, J as nameBridges, K as hasBridge, M as importSource, N as importedComponents, O as entryClasses, P as resolveRelative, Q as getLocation, R as forEachNode, T as builtin, U as walk, _ as functionId, a as scopeLabel, b as SHARED_QUERY, f as instanceScope, i as report, k as refreshedNames, n as formatReport, p as slotIndex, q as mayHaveBridge, s as compile, t as anchorLabel, v as getComponentName, w as resolveFromDisk, x as generateShared, y as hash, z as analyze } from "./inspect-B9cRF6AM.js";
2
2
  import { s as toNodeHeaders } from "./cookies-Cnbf4w-S.js";
3
3
  import { t as LOGO } from "./logo-DQ_OYhBi.js";
4
- import { _ as reachableFiles, a as findServerFiles, c as hasServerMiddleware, d as serverExports, f as serverModule, g as packageFileName, h as findPackages, i as findScripts, l as hasUseServer, m as findPackage, n as defaultExclude, o as findPackageServerFile, p as serverStubs, r as findFiles, u as isScriptFile, v as resolveComponentPackage } from "./files-DtDH5AR4.js";
4
+ import { _ as findPackages, a as findScripts, b as resolveComponentPackage, d as isScriptFile, f as serverExports, g as findPackage, h as findBridgePackages, i as findFiles, l as hasServerMiddleware, m as serverStubs, n as defaultExclude, o as findServerFiles, p as serverModule, r as findBridgeFiles, s as findPackageServerFile, u as hasUseServer, v as packageFileName, y as reachableFiles } from "./files-XX5yW3KL.js";
5
5
  import { parseSync } from "oxc-parser";
6
6
  import { createHash } from "node:crypto";
7
7
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
@@ -129,7 +129,9 @@ function noFeatures() {
129
129
  routes: false,
130
130
  loading: false,
131
131
  rootWait: false,
132
- searchParams: false
132
+ searchParams: false,
133
+ stores: false,
134
+ bridges: false
133
135
  };
134
136
  }
135
137
  /** Every feature, for a build that compiles components in the browser. */
@@ -163,7 +165,9 @@ function getFeatures(result) {
163
165
  routes: /\b(?:routeContext|navigationContext)\b/.test(all),
164
166
  loading: /\$\$b\.loading\(/.test(client),
165
167
  rootWait: /\$\$b\.wait\(/.test(client),
166
- searchParams: /\$\$b\.(?:searchParam|paramEffect)\(/.test(all)
168
+ searchParams: /\$\$b\.(?:searchParam|paramEffect)\(/.test(all),
169
+ stores: /\$\$(?:b|ctx)\.(?:toStore|consumeStore)\(|['"]brumate\/store['"]/.test(all),
170
+ bridges: /\$\$nameBridge\(/.test(all)
167
171
  };
168
172
  }
169
173
  /** The features of several components together. */
@@ -187,6 +191,8 @@ function joinFeatures(all) {
187
191
  joined.loading ||= features.loading;
188
192
  joined.rootWait ||= features.rootWait;
189
193
  joined.searchParams ||= features.searchParams;
194
+ joined.stores ||= features.stores;
195
+ joined.bridges ||= features.bridges;
190
196
  }
191
197
  return joined;
192
198
  }
@@ -208,7 +214,9 @@ const GLOBALS = {
208
214
  routes: "__BRUMATE_HAS_ROUTES__",
209
215
  loading: "__BRUMATE_HAS_LOADING__",
210
216
  rootWait: "__BRUMATE_HAS_ROOT_WAIT__",
211
- searchParams: "__BRUMATE_HAS_SEARCH_PARAMS__"
217
+ searchParams: "__BRUMATE_HAS_SEARCH_PARAMS__",
218
+ stores: "__BRUMATE_HAS_STORES__",
219
+ bridges: "__BRUMATE_HAS_BRIDGES__"
212
220
  };
213
221
  /** True for code that reads a feature, such as the core. */
214
222
  function readsFeatures(code) {
@@ -1830,6 +1838,10 @@ function packagesKey(list) {
1830
1838
  ]);
1831
1839
  return JSON.stringify(rows);
1832
1840
  }
1841
+ /** The names of a `noExternal` setting as a list. */
1842
+ function toList(value) {
1843
+ return Array.isArray(value) ? value : [];
1844
+ }
1833
1845
  /** Skips the `node_modules` and hidden directories of a package of components. */
1834
1846
  function packageExclude(directory) {
1835
1847
  return directory === "node_modules" || directory.startsWith(".");
@@ -2007,6 +2019,8 @@ function brumate(options = {}) {
2007
2019
  let refreshed;
2008
2020
  /** The dependencies of the app that ship `.brm` files. See `packages.ts`. */
2009
2021
  let packages = [];
2022
+ /** Installed packages with a `bridge`, which are not packages of components, and their files. */
2023
+ let bridgePackages = [];
2010
2024
  function relative(file) {
2011
2025
  return normalizePath(path.relative(root, file));
2012
2026
  }
@@ -2025,6 +2039,8 @@ function brumate(options = {}) {
2025
2039
  }
2026
2040
  /** Files of server functions: scripts whose first statement is `'use server'`, by ID. */
2027
2041
  const serverFiles = /* @__PURE__ */ new Map();
2042
+ /** The script files with a `bridge`, by the ID of their module. The browser loads them by it. */
2043
+ const bridgeFiles = /* @__PURE__ */ new Map();
2028
2044
  /** The scripts of the app, when it uses packages of components. */
2029
2045
  let appScripts = [];
2030
2046
  /** The ID of a function that a component imports from a 'use server' file, by a relative path. */
@@ -2048,6 +2064,12 @@ function brumate(options = {}) {
2048
2064
  }
2049
2065
  return found && functionId(serverFileId(normalizePath(found)), name, !isServe);
2050
2066
  }
2067
+ function bridgeId(file) {
2068
+ let normalized = normalizePath(file);
2069
+ if (bridgePackages.length > 0 && normalized.includes("/node_modules/") && existsSync(normalized)) normalized = normalizePath(realpathSync(normalized));
2070
+ for (const item of bridgePackages) if (normalized.startsWith(`${item.root}/`)) return bridgeModuleId(`${item.name}/${normalized.slice(item.root.length + 1)}`);
2071
+ return bridgeModuleId(getFileName(file));
2072
+ }
2051
2073
  function serverFileId(file) {
2052
2074
  return `${path.basename(file).replace(/\.[^.]+$/, "")}_${hash(getFileName(file))}`;
2053
2075
  }
@@ -2062,6 +2084,7 @@ function brumate(options = {}) {
2062
2084
  return !findPackage(packages, file);
2063
2085
  }
2064
2086
  const searches = [findFiles(root, exclude), findServerFiles(root, exclude)];
2087
+ const bridged = Promise.all([findBridgeFiles(root, exclude), ...directories.map((directory) => findBridgeFiles(directory, packageExclude))]);
2065
2088
  for (const directory of directories) searches.push(findFiles(directory, packageExclude), findServerFiles(directory, packageExclude));
2066
2089
  const [own, ownServer, ...found] = await Promise.all(searches);
2067
2090
  const scripts = [];
@@ -2071,6 +2094,9 @@ function brumate(options = {}) {
2071
2094
  appScripts = scripts;
2072
2095
  files.clear();
2073
2096
  serverFiles.clear();
2097
+ bridgeFiles.clear();
2098
+ for (const list of await bridged) for (const file of list) bridgeFiles.set(bridgeId(file), file);
2099
+ for (const item of bridgePackages) for (const file of item.files) bridgeFiles.set(bridgeId(file), file);
2074
2100
  for (const file of own) if (ownFile(file)) files.set(componentId(file), file);
2075
2101
  for (const file of ownServer) if (ownFile(file)) serverFiles.set(serverFileId(file), file);
2076
2102
  for (const [index, list] of found.entries()) for (const file of list) if (index % 2 === 0) files.set(componentId(file), file);
@@ -2145,10 +2171,14 @@ function brumate(options = {}) {
2145
2171
  break;
2146
2172
  }
2147
2173
  features.lateMarkup ||= options.navigate !== false || loading;
2174
+ features.bridges ||= bridgeFiles.size > 0;
2175
+ features.stores ||= features.bridges;
2148
2176
  features.routes ||= options.navigate !== false;
2149
2177
  if (!features.routes) {
2150
2178
  const own = path.resolve(import.meta.dirname, "..").split(path.sep).join("/");
2151
- const texts = await inBatches([.../* @__PURE__ */ new Set([...await findScripts(root, exclude), ...reachable()])].filter((file) => !file.startsWith(`${own}/dist/`) && !file.startsWith(`${own}/src/`)), (file) => readFile(file, "utf8").catch(() => ""));
2179
+ const scripts = [];
2180
+ for (const file of /* @__PURE__ */ new Set([...await findScripts(root, exclude), ...reachable()])) if (!file.startsWith(`${own}/dist/`) && !file.startsWith(`${own}/src/`)) scripts.push(file);
2181
+ const texts = await inBatches(scripts, (file) => readFile(file, "utf8").catch(() => ""));
2152
2182
  for (const text of texts) if (ROUTE_CONTEXTS.test(text)) {
2153
2183
  features.routes = true;
2154
2184
  break;
@@ -2306,6 +2336,13 @@ function brumate(options = {}) {
2306
2336
  let builtHints;
2307
2337
  /** The IDs of the components in each bundle of the client build, by root, for `hints.json`. */
2308
2338
  const bundleMembers = /* @__PURE__ */ new Map();
2339
+ /** `bridges`: the loaders of the modules with a `bridge`, by module ID. */
2340
+ function bridgeLoaders() {
2341
+ const lines = ["const bridges = {"];
2342
+ for (const [id, file] of bridgeFiles) lines.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(file)}),`);
2343
+ lines.push("};");
2344
+ return lines.join("\n");
2345
+ }
2309
2346
  async function manifest() {
2310
2347
  const list = [...files];
2311
2348
  const needed = await inBatches(list, async ([, file]) => isServe || (await compileFile(file)).result.clientCode);
@@ -2324,6 +2361,14 @@ function brumate(options = {}) {
2324
2361
  }
2325
2362
  bundleMembers.set(root, ids);
2326
2363
  }
2364
+ if (bridgeFiles.size > 0) return [
2365
+ "import { load as loadBundle } from 'brumate/bundles';",
2366
+ bridgeLoaders(),
2367
+ "export function load(id) {",
2368
+ " return bridges[id] ? bridges[id]() : loadBundle(id);",
2369
+ "}",
2370
+ `load.all = () => import(${JSON.stringify(BUNDLES)});`
2371
+ ].join("\n");
2327
2372
  return [
2328
2373
  "import { load } from 'brumate/bundles';",
2329
2374
  `load.all = () => import(${JSON.stringify(BUNDLES)});`,
@@ -2333,10 +2378,19 @@ function brumate(options = {}) {
2333
2378
  const entries = [];
2334
2379
  for (const [id, file] of kept) entries.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(`${file}${CLIENT_QUERY}`)}),`);
2335
2380
  return [
2381
+ ...bridgeFiles.size > 0 ? [bridgeLoaders()] : [],
2336
2382
  "const modules = {",
2337
2383
  ...entries,
2338
2384
  "};",
2339
2385
  "export function load(id) {",
2386
+ ...bridgeFiles.size > 0 ? [
2387
+ " if (bridges[id]) {",
2388
+ " return bridges[id]();",
2389
+ " }"
2390
+ ] : [],
2391
+ " if (id.startsWith('bridge:')) {",
2392
+ " id = id.slice(7);",
2393
+ " }",
2340
2394
  ...isServe ? [
2341
2395
  " const module = modules[id];",
2342
2396
  " if (!module) {",
@@ -2488,6 +2542,21 @@ function brumate(options = {}) {
2488
2542
  const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2489
2543
  return where ? `${site.label} ${where.line}:${where.column}` : site.label;
2490
2544
  }
2545
+ const moduleSources = /* @__PURE__ */ new Map();
2546
+ function placeOf(offset) {
2547
+ const at = result.locate(offset);
2548
+ if (at.file === void 0) return getLocation(source, at.offset);
2549
+ if (!moduleSources.has(at.file)) try {
2550
+ moduleSources.set(at.file, readFileSync(at.file, "utf8"));
2551
+ } catch {
2552
+ moduleSources.set(at.file, void 0);
2553
+ }
2554
+ const text = moduleSources.get(at.file);
2555
+ return text === void 0 ? void 0 : {
2556
+ ...getLocation(text, at.offset),
2557
+ file: at.file
2558
+ };
2559
+ }
2491
2560
  const liveSites = /* @__PURE__ */ new Set();
2492
2561
  for (const node of plan.graph.live) if ("site" in node) liveSites.add(node.site);
2493
2562
  for (const layout of plan.scopes.values()) {
@@ -2514,20 +2583,22 @@ function brumate(options = {}) {
2514
2583
  const graphNodes = [];
2515
2584
  for (const node of nodes) {
2516
2585
  if (node.kind === "source" || node.kind === "memo") {
2586
+ const at = placeOf(node.declaration.range.start);
2517
2587
  graphNodes.push({
2518
2588
  kind: node.kind === "memo" ? "memo" : node.declaration.kind,
2519
2589
  label: node.declaration.name,
2520
2590
  scope: instanceScope(plan, node.declaration.scope).id,
2521
- slot: slotIndex(plan, node.declaration)
2591
+ slot: slotIndex(plan, node.declaration),
2592
+ ...at ? { at } : {}
2522
2593
  });
2523
2594
  continue;
2524
2595
  }
2525
- const at = result.locate(node.site.range.start);
2526
- const where = at.file === void 0 ? getLocation(source, at.offset) : void 0;
2596
+ const at = placeOf(node.site.range.start);
2527
2597
  graphNodes.push({
2528
2598
  kind: node.kind,
2529
- label: where ? `${node.site.label} ${where.line}:${where.column}` : node.site.label,
2530
- scope: instanceScope(plan, node.site.scope).id
2599
+ label: node.site.label,
2600
+ scope: instanceScope(plan, node.site.scope).id,
2601
+ ...at ? { at } : {}
2531
2602
  });
2532
2603
  }
2533
2604
  const graphEdges = [];
@@ -2859,9 +2930,36 @@ function brumate(options = {}) {
2859
2930
  return {
2860
2931
  name: "brumate",
2861
2932
  enforce: "pre",
2862
- config(config, env) {
2863
- packages = findPackages(path.resolve(config.root ?? process.cwd()));
2933
+ async config(config, env) {
2934
+ const appRoot = path.resolve(config.root ?? process.cwd());
2935
+ packages = findPackages(appRoot);
2936
+ bridgePackages = [];
2937
+ for (const item of findBridgePackages(appRoot)) {
2938
+ const files = await findBridgeFiles(item.root, packageExclude);
2939
+ if (files.length > 0) bridgePackages.push({
2940
+ ...item,
2941
+ files
2942
+ });
2943
+ }
2864
2944
  const shared = packageConfig(config);
2945
+ if (bridgePackages.length > 0) {
2946
+ const names = [...new Set(bridgePackages.map((item) => item.package))];
2947
+ const excluded = /* @__PURE__ */ new Set([...shared.optimizeDeps?.exclude ?? [], ...names]);
2948
+ const nested = [];
2949
+ for (const item of bridgePackages) for (const dependency of item.dependencies) if (!excluded.has(dependency)) nested.push(`${item.package} > ${dependency}`);
2950
+ shared.optimizeDeps = {
2951
+ include: [...shared.optimizeDeps?.include ?? [], ...new Set(nested)],
2952
+ exclude: [...shared.optimizeDeps?.exclude ?? [], ...names]
2953
+ };
2954
+ shared.ssr = {
2955
+ ...shared.ssr,
2956
+ noExternal: [...toList(shared.ssr?.noExternal), ...names]
2957
+ };
2958
+ shared.resolve = {
2959
+ ...shared.resolve,
2960
+ dedupe: ["brumate"]
2961
+ };
2962
+ }
2865
2963
  const hmr = config.server?.hmr;
2866
2964
  if (env.command === "serve" && options.devtools !== false && hmr !== false && (typeof hmr !== "object" || hmr.overlay === void 0)) shared.server = { hmr: { overlay: false } };
2867
2965
  if (!env.isSsrBuild) {
@@ -3272,6 +3370,15 @@ function brumate(options = {}) {
3272
3370
  } catch (error) {
3273
3371
  this.error(error.message);
3274
3372
  }
3373
+ if (file && isScriptFile(file) && mayHaveBridge(code)) try {
3374
+ const named = nameBridges(code, file, bridgeId(file));
3375
+ if (named) return {
3376
+ code: named,
3377
+ map: null
3378
+ };
3379
+ } catch (error) {
3380
+ this.error(error.message);
3381
+ }
3275
3382
  const shared = isReactiveModule(file ?? "") && id.endsWith("?brumate-shared");
3276
3383
  if (!file?.endsWith(".brm") && !shared) return;
3277
3384
  const result = await transformWithOxc(code, `${file}.ts`, {
@@ -3312,6 +3419,14 @@ function brumate(options = {}) {
3312
3419
  appScripts = rest;
3313
3420
  if (event !== "unlink") appScripts.push(normalized);
3314
3421
  }
3422
+ const bridged = bridgeId(normalized);
3423
+ const hadBridge = bridgeFiles.has(bridged);
3424
+ const nowBridge = event !== "unlink" && existsSync(file) && hasBridge(readFileSync(file, "utf8"), file);
3425
+ if (nowBridge) bridgeFiles.set(bridged, normalized);
3426
+ else bridgeFiles.delete(bridged);
3427
+ if (hadBridge !== nowBridge) {
3428
+ for (const module of server.moduleGraph.idToModuleMap.values()) if (module.id === `\0${MANIFEST}`) server.moduleGraph.invalidateModule(module);
3429
+ }
3315
3430
  const id = serverFileId(normalized);
3316
3431
  const before = serverFiles.has(id);
3317
3432
  const after = event !== "unlink" && existsSync(file) && hasUseServer(readFileSync(file, "utf8"));