@tokamaq/build 0.0.0-stage → 0.1.0-dev.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pixelscortex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,347 @@
1
- # Temporary Holding Version
1
+ # Tokamaq artifact build
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build a plugin artifact by passing its folder to the builder:
4
+
5
+ ```sh
6
+ proto run bun -- packages/build/src/build.ts /path/to/plugin-source
7
+ ```
8
+
9
+ ## Building outside the checkout
10
+
11
+ Install the development packages with Bun:
12
+
13
+ ```sh
14
+ bun add @tokamaq/sdk@dev @tokamaq/build@dev @tokamaq/ui@dev @tokamaq/runtime@dev
15
+ bun run tokamaq-build <plugin-folder>
16
+ ```
17
+
18
+ For a Solid window, add `solid-js@2.0.0`, `@solidjs/web@2.0.0` and any packages
19
+ the window imports. For type checking with the SDK's window config, add
20
+ `typescript@5.9.3`, `vite@8.3.6` and `@types/node@26.6.6` as dev dependencies.
21
+ Stylesheets that import Tailwind need `tailwindcss` (the bundled plugins use
22
+ `4.3.5`).
23
+
24
+ ## Building with workspace links
25
+
26
+ Install the Tokamaq checkout's workspace dependencies with
27
+ `proto run bun -- install --frozen-lockfile`. In the plugin or its parent
28
+ workspace's `node_modules/@tokamaq/`, link `sdk`, `build`, `ui` and `runtime`
29
+ to the checkout's corresponding `packages/` directories. Keep the links pointing
30
+ to the real checkout so the builder and SDK can resolve their installed tools
31
+ (Vite, TypeScript, the Solid compiler and Tailwind's compiler and scanner).
32
+
33
+ Install the third-party packages that plugin source imports in the plugin
34
+ workspace. For a Solid window, use `solid-js@2.0.0` and `@solidjs/web@2.0.0`;
35
+ for window type checking, also install `vite@8.3.6` and `@types/node@26.6.6`.
36
+ Stylesheets that import Tailwind need `tailwindcss` there too (the bundled
37
+ plugins use `4.3.5`). A setup using the checkout's existing installs can
38
+ symlink these individual dependency directories instead.
39
+
40
+ ```sh
41
+ bun node_modules/@tokamaq/build/src/build.ts <plugin-folder>
42
+ ```
43
+
44
+ Use Bun 1.4.4, as pinned by the checkout. The plugin folder can be absolute or
45
+ relative to the current directory.
46
+ Extend `@tokamaq/sdk/tsconfig.server.json` for server code and
47
+ `@tokamaq/sdk/tsconfig.window.json` for window code. If the plugin has no server
48
+ config, the builder uses the SDK's server base. Window tests can import
49
+ `@tokamaq/build/window-test-config` and `@tokamaq/build/client-surface`.
50
+
51
+ Keep source for plugins imported as `plugin:<id>/server` or `plugin:<id>/client`
52
+ in sibling folders named by ID. The builder looks for dependency manifests
53
+ beside the plugin, in the configured plugin catalog, or in `TOKAMAQ_PLUGIN_DIR`.
54
+
55
+ ## Artifacts
56
+
57
+ The builder reads literal `plugin.ts` metadata, bundles `src/server/` through the
58
+ SDK compiler, derives public function references and provider contracts, and
59
+ writes a versioned `dist/manifest.json` with hashes of final emitted bytes.
60
+ The transaction bundle contains queries and mutations. The action process
61
+ loads server actions from the full server bundle.
62
+ Unchanged output preserves bytes and modification times. The manifest is
63
+ published last; installation still needs its own complete-artifact staging.
64
+
65
+ The UI target emits browser ESM in `ui.js` and `ui.js.map`, compiled with Solid 2
66
+ DOM JSX. `ui: false` explicitly disables the
67
+ UI target; `backend: false` disables the server target. The server output is declared in `entries.server`.
68
+ Client `styles.css` is discovered beside the client entry and compiled with
69
+ Tailwind. Imported CSS is also collected by Vite. No registration wrapper or
70
+ HTML shell is emitted.
71
+
72
+ `entries.ui` is `{ "code": "ui.js", "map": "ui.js.map", "css": "styles.css" }`;
73
+ `css` is omitted when no stylesheet is emitted. Contributions and qualified
74
+ slot/component names still come from the compiler, without executing the client.
75
+ Final file hashes cover JavaScript, source maps, CSS and server output.
76
+
77
+ Shared imports remain bare: `solid-js`, `solid-js/*`, `@solidjs/web` (including
78
+ subpaths), `@tokamaq/sdk` (including subpaths), `@tokamaq/ui` (including subpaths),
79
+ `@tokamaq/runtime/router`, `@ui-sdk/solid` and `@ui-sdk/core` (including subpaths),
80
+ and compiler-emitted `@plugins/*` module names. Authors use
81
+ `import { Panel } from "plugin:example/client"`. The compiler emits
82
+ `@plugins/example/ui`; the web loader resolves it to the dependency's
83
+ revision-pinned module, including literal dynamic imports. Static imports infer
84
+ required dependencies; literal dynamic imports infer optional dependencies.
85
+
86
+ The catalog keeps existing manifest fields and adds `revision`, `installOrder`,
87
+ `uiUrl` and `stylesheetUrl` per plugin. URLs are `/plugins/<id>/<catalog revision>/assets/<name>`;
88
+ plugins without UI or CSS have null URLs. Only manifest-declared UI assets from
89
+ the current verified snapshot are served. Stale revisions return 404. Successful
90
+ assets use `private, max-age=31536000, immutable` caching and JavaScript uses
91
+ `text/javascript`.
92
+
93
+ Asset GET, catalog GET and WebSocket upgrades accept exactly the origins in
94
+ `TOKAMAQ_ALLOWED_ORIGINS` (comma-separated, replacing the defaults):
95
+ `tauri://localhost`, `http://tauri.localhost`, `http://127.0.0.1:1420`.
96
+ Other origins receive 403. Requests without Origin remain supported.
97
+ Desktop mode requires the existing local token. The window sends
98
+ `Authorization: Bearer …` for HTTP, including asset and stylesheet fetches.
99
+ It applies the fetched CSS as a constructed stylesheet, which it removes
100
+ when the plugin generation retires.
101
+ On browser WebSocket upgrades it offers `tokamaq` and
102
+ `tokamaq.bearer.<percent-encoded token>` as subprotocols; the server selects
103
+ only `tokamaq`. Missing or wrong credentials receive 401. Tokenless loopback development exposes these routes too,
104
+ with the same origin checks. Control routes remain native-only and require
105
+ header authorization in desktop mode.
106
+
107
+ Run the focused build tests from this directory with `sh tests/run.sh`.
108
+ The browser fixture lives in `tests/fixtures/browser`; its optional cross-plugin
109
+ module need not be installed to build or serve it.
110
+ After building `target/debug/tokamaq-server`, run the real curl/WebSocket checks from the
111
+ repository root with `proto run bun -- packages/build/tests/browser-assets.mjs`.
112
+ They cover loopback, desktop token authentication and a configured origin list.
113
+
114
+ ## Plugin imports
115
+
116
+ Production source (server, window and caller actions; tests excluded) must stay inside
117
+ its own plugin folder. Relative paths, absolute paths, source aliases and
118
+ symlinks cannot reach another folder. Dependencies installed through
119
+ `node_modules`, including workspace packages, are allowed; another plugin's
120
+ implementation is never a package dependency.
121
+
122
+ Use a sibling plugin's public API through sanctioned specifiers:
123
+
124
+ ```ts
125
+ import { api as chat, type ToolPart } from "plugin:chat/server";
126
+ // Inside an action: host routing and can_call still govern every operation.
127
+ await ctx.use(chat).updateRun({ runId, token, delta: "Hello" });
128
+ ```
129
+
130
+ `plugin:<id>/server` and its shorthand `plugin:<id>` expose public types from
131
+ that plugin's `src/server/api.ts` and generated references for its exported
132
+ queries, mutations and actions. The `api` object uses the public export names;
133
+ named imports also carry references. No runtime helpers or handlers cross the
134
+ boundary. Public APIs are inspected
135
+ statically and are never executed by the builder.
136
+
137
+ `plugin:<id>/tables` exposes generated handles for the tables in a sibling
138
+ plugin's server schema. Add the owner to `depends` to use one in `v.ref`. The
139
+ builder makes a local type copy in `.tokamaq/types/<id>/tables.d.ts` and emits
140
+ only qualified table names at runtime. Do not check in or hand edit the copy.
141
+
142
+ Within a plugin, use `src/server/_generated/api.ts` from the window. Its runtime
143
+ references contain only public names. The window build refuses imports of other
144
+ server code, including `_generated/internal.ts`. Internal definitions cannot be
145
+ re-exported through the public server entry. Commit both generated files.
146
+
147
+ `plugin:<id>/client` compiles to the internal module name `@plugins/<id>/ui`.
148
+ Authors use only `plugin:<id>/client`; authored `@plugins/*` imports are rejected.
149
+ Static imports declare dependencies and literal dynamic imports declare optional
150
+ dependencies. The web loader rewrites both to revision-owned browser modules.
151
+ Public client types come from `src/client/api.ts` or `src/client/api.tsx`.
152
+
153
+ The builder generates ignored type facades in `.tokamaq/types` and configures
154
+ its checkers automatically. For editor checking outside the builder, add these
155
+ paths to the plugin's tsconfig (relative to the plugin root):
156
+
157
+ ```json
158
+ {
159
+ "compilerOptions": {
160
+ "paths": {
161
+ "plugin:*/server": [".tokamaq/types/*/server.d.ts"],
162
+ "plugin:*/client": [".tokamaq/types/*/client.d.ts"],
163
+ "plugin:*": [".tokamaq/types/*/server.d.ts"]
164
+ }
165
+ }
166
+ }
167
+ ```
168
+
169
+ The current authoring build requires sibling public source APIs for type and
170
+ reference metadata; installed artifacts remain independent of that source.
171
+
172
+ ## Extending a screen
173
+
174
+ Build the owner plugin to publish a typed `find` on its public client API.
175
+ Searches look at that plugin's authored JSX, including UI it contributes to
176
+ other plugins. Each element is named by its nonempty static `data-part`,
177
+ then its static `id`, then its tag or component name (such as `Menu.Item`).
178
+ `data-part-ignore` excludes an element and its descendants.
179
+
180
+ If a name has several matches, narrow it with `in` to an enclosing render
181
+ function or element. Solid control flow and fragments are transparent.
182
+ You can also narrow a name by static `type`, `href`, `role`, and `aria-*`
183
+ attributes. Write ARIA keys without the prefix, for example
184
+ `find("button", { aria: { label: "Stop" } })`. The typed API offers the
185
+ attribute filters and values the owner writes for that name. Computed JSX
186
+ values, class, style, data attributes and text cannot match a filter, and
187
+ neither can an attribute written before a spread, which can replace it. A
188
+ value is matched as written in the source: `aria-label="Save &amp; quit"` is
189
+ found with `"Save &amp; quit"`.
190
+
191
+ Filters must all match. If the search is still ambiguous, use `nth` to select
192
+ a 1-based position among the remaining matches in source order. The name
193
+ and filters in the search must be literals. If the search does not identify
194
+ exactly one element, the build fails and lists the candidates.
195
+
196
+ When an add-on finds a plain tag without a static `data-part` or `id`,
197
+ both builds warn and suggest adding `data-part`. The owner's build reports
198
+ this once per installed add-on and target.
199
+
200
+ Commit the generated `_generated/components.d.ts` next to the client entry.
201
+ Export actions from the contributing plugin's client entry:
202
+
203
+ ```tsx
204
+ import { after } from "@tokamaq/sdk/client";
205
+ import * as chat from "plugin:chat/client";
206
+
207
+ export const Branch = after(chat.find("title", { in: "Header" }), BranchChip);
208
+ ```
209
+
210
+ `before` and `after` render siblings. `prepend` and `append` render inside
211
+ elements that accept children.
212
+
213
+ Use `layer(target, (props, Original) => …)` to take over the element.
214
+ Render `<Original />` to draw the next layer down, or the owner's element
215
+ at the bottom. Pass children to change the contents without changing the
216
+ element or its attributes. Put `<Original.Children />` inside `<Original>` to
217
+ draw the contents that would appear without this layer: the children supplied
218
+ by an outer layer, or the owner's contents with other plugins' `prepend` and
219
+ `append`. Draw `Original` and `Original.Children` once at a time. A layer may have two
220
+ uses of `Original` in two branches and switch between them: the element is
221
+ handed over and stays mounted. If both are drawn at once, only the last one
222
+ shows, with a warning.
223
+ If no layer draws `Original`, the owner's element is unloaded. While a layer
224
+ supplies the contents, the owner's plain tags inside keep their DOM nodes,
225
+ but components inside mount again each time the contents change hands, so
226
+ their own state starts over. A layer with a
227
+ false `when` passes through.
228
+ Layers run outermost first by plugin install order, then `order` (default
229
+ 0), plugin ID, and export name. `before` and `after` stay outside all layers;
230
+ `hide` also removes those sibling additions.
231
+
232
+ Use `attrs(target, (props, current) => values, options?)` to change HTML
233
+ attributes on a plain element or props on a component. The callback and
234
+ `when` are live and receive the owning render function's props. `current`
235
+ contains the owner's values plus earlier actions, sorted by install order,
236
+ then `order`, plugin ID, and export name. Class strings are added to existing
237
+ classes, including the owner's Solid class objects and arrays. For other
238
+ keys, a defined value overrides `current`; omit the key or return `undefined`
239
+ to leave it alone. If another add-on already set a key, read `current` for
240
+ that key to combine the values and avoid an overwrite warning. For plain
241
+ HTML attributes, `current` reads booleans as true when present and false when
242
+ absent, and other attributes as strings or `undefined` when absent.
243
+
244
+ ```tsx
245
+ import { attrs } from "@tokamaq/sdk/client";
246
+ import * as chat from "plugin:chat/client";
247
+
248
+ export const Busy = attrs(chat.find("article", { in: "Message" }), (props) => ({
249
+ "aria-busy": props.message.status === "streaming",
250
+ }));
251
+ ```
252
+
253
+ Give `Original` attributes with the same rules: `<Original class="dim" />`
254
+ adds a class after `attrs` has run. These attributes only apply if the layers
255
+ below draw the owner's element. You can't change identifiers (`id`,
256
+ `data-part`, `data-part-ignore`), refs, content as an attribute, event
257
+ handlers, or function props. Pass JSX children to `Original` to replace
258
+ its contents. Rebuild the owner to publish the attribute types for its
259
+ elements.
260
+
261
+ The overlay tracks writes through `setAttribute`, `removeAttribute`,
262
+ `toggleAttribute`, `classList`, `className`, `style`, and form-state properties.
263
+ Writes through other DOM properties (such as `el.title`, JSX `prop:title`,
264
+ `dataset`, and ARIA reflection) bypass it, so the owner's write shows during
265
+ the override and ending the override may restore a stale value.
266
+
267
+ Actions and their live `when` option receive the
268
+ props of the render function that owns the tag. Parts inside an inline list
269
+ callback get `props.$row.item` and `props.$row.index`, typed as Solid passes
270
+ them to that callback. Nested rows expose the enclosing row as `$row.parent`.
271
+ With `Index` (or Solid 2’s `For keyed={false}`), the item is an accessor and
272
+ the index is a number.
273
+
274
+ An add-on's manifest records both the search and the element selected at
275
+ build time. When the owner changes, a search keeps its original match if
276
+ possible, or follows the only remaining match. If a search cannot be
277
+ resolved, the owner's build warns with the add-on ID and the window skips
278
+ the placement and raises an alert. A search with `nth` stays on the element
279
+ it found: when the owner's change puts another element at that position, the
280
+ placement is skipped, never moved. Give a target a `data-part` to avoid
281
+ relying on position.
282
+
283
+ A positional segment hashes the tag, the attributes `role`, `type`, `name`,
284
+ `for` and `href` (each by its static string value or as "an expression"),
285
+ and any `aria-*` attribute that has a static string value. It ignores every
286
+ other attribute, including `class`, `style`, `data-*`, computed `aria-*`,
287
+ event handlers, `ref`, spread attributes, and the source text of
288
+ expressions. If two positional siblings
289
+ still have the same identity, a swap of the two cannot be seen; an add-on
290
+ build that picks one of them with `nth` warns that the target is ambiguous
291
+ and asks the owner for a `data-part` or `id`.
292
+
293
+ Use `attach(owner.find("Composer"), TrackComposer, { when })` to run a
294
+ component for each mounted instance of the owner's named render function.
295
+ It receives live props and can use effects, cleanup, context, and shell
296
+ regions such as `Region.Panel`. Returned JSX is evaluated without drawing in
297
+ place. Hiding or layering an element inside the function leaves the attachment
298
+ running. An attachment stops and cleans up when its instance leaves, `when`
299
+ becomes false, or it throws. Failures are warned once per plugin and export.
300
+
301
+ For `attach`, `find` searches only render functions; placements search only
302
+ elements. Use `in` for an enclosing render function and `nth` to pick a
303
+ position; attribute filters apply to elements. Attachments start in plugin
304
+ install order, then `order`, plugin ID, and export name. Owner updates
305
+ recheck the match and warn when an attachment can no longer resolve.
306
+
307
+ ### Plugin alerts
308
+
309
+ The active view's **Plugin alerts** list reports:
310
+
311
+ - A search that no longer matches its intended element or render function.
312
+ - A layer that omits `Original` and covers another plugin's lower layer,
313
+ inside placement, attributes, or action on a descendant.
314
+ - A layer that draws `Original` with its own children and leaves out
315
+ `Original.Children`: other plugins' inside placements and their actions on
316
+ descendants are gone, though the element and the layers below are not.
317
+ - A `hide` that removes another plugin's action on the element or a descendant.
318
+ Two plugins hiding the same element lose nothing to each other.
319
+ - An addition, layer, attribute callback, attachment, or `when` that throws.
320
+ The alert names the plugin and export; the owner can still render.
321
+ - Attribute problems: overwriting another plugin's value without reading
322
+ `current`, setting a forbidden attribute, or targeting an old owner that
323
+ must be rebuilt.
324
+
325
+ Cover and hide alerts name both plugins and clear when the action no longer
326
+ causes the loss. Multiple mounted instances share a single alert. Failures
327
+ stay in the list until the failing plugin is removed or reloaded.
328
+
329
+ A descendant here is an element written inside the covered or hidden element
330
+ in the same render function. An action on an element of a component that is
331
+ only used inside it (the `button` inside a `<SendButton />`) is lost in the
332
+ same way but is not listed.
333
+
334
+ ### Contract registrations
335
+
336
+ `src/contracts.ts` declares named public contract keys. A
337
+ `plugin:<id>/contracts` import compiles to a key and type references only; it
338
+ never includes the provider or defining plugin's executable code. Optional
339
+ dependencies can build with a checked-in copy of the public declarations at
340
+ `contracts/<id>.ts` if the defining plugin's source is absent. The compiler
341
+ checks each exported `provide(...)` against the declaration and requires the
342
+ defining plugin in `depends` or `optional`. The artifact records declarations
343
+ and registrations in `contracts` and `contractProviders`, and includes
344
+ implementation code only in the declared local or server lane.
345
+
346
+ Generated `_generated/plugin.ts` contains references for `pluginOnly(...)`
347
+ functions when present. Commit it along with `api.ts` and `internal.ts`.
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@tokamaq/build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-dev.1",
4
+ "description": "Build tools for Tokamaq plugin artifacts.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pixelscortex/tokamaq.git",
9
+ "directory": "packages/build"
10
+ },
11
+ "bin": {
12
+ "tokamaq-build": "./src/build.ts"
13
+ },
14
+ "files": [
15
+ "src/artifact-bundle.ts",
16
+ "src/auth-dependencies.ts",
17
+ "src/build.ts",
18
+ "src/client-surface.ts",
19
+ "src/compiler.ts",
20
+ "src/component-parts.ts",
21
+ "src/contributions.ts",
22
+ "src/css.ts",
23
+ "src/descriptor.ts",
24
+ "src/exports.ts",
25
+ "src/hook-targets.ts",
26
+ "src/part-props.ts",
27
+ "src/plugin-boundary.ts",
28
+ "src/ui-build-config.ts",
29
+ "src/vite.ts",
30
+ "src/window-state.ts",
31
+ "src/window-test-config.ts"
32
+ ],
33
+ "type": "module",
34
+ "exports": {
35
+ "./vite": "./src/vite.ts",
36
+ "./css": "./src/css.ts",
37
+ "./window-test-config": "./src/window-test-config.ts",
38
+ "./client-surface": "./src/client-surface.ts"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public",
42
+ "tag": "dev"
43
+ },
44
+ "dependencies": {
45
+ "@solidjs/vite-plugin": "3.0.0",
46
+ "@tailwindcss/node": "4.3.4",
47
+ "@tailwindcss/oxide": "4.3.4",
48
+ "magic-string": "0.30.21",
49
+ "tailwindcss": "4.3.4",
50
+ "typescript": "5.9.3",
51
+ "vite": "8.3.6"
52
+ },
53
+ "devDependencies": {
54
+ "@solidjs/web": "2.0.0",
55
+ "@types/node": "26.6.6",
56
+ "jsdom": "31.0.1",
57
+ "solid-js": "2.0.0",
58
+ "vitest": "5.1.0"
59
+ },
60
+ "peerDependencies": {
61
+ "@tokamaq/sdk": "0.1.0-dev.1",
62
+ "@tokamaq/ui": "0.1.0-dev.1",
63
+ "solid-js": "2.0.0"
64
+ },
65
+ "peerDependenciesMeta": {
66
+ "@tokamaq/ui": {
67
+ "optional": true
68
+ },
69
+ "solid-js": {
70
+ "optional": true
71
+ }
72
+ }
73
+ }
@@ -0,0 +1,86 @@
1
+ import ts from "typescript";
2
+ import { definePlugin, type PluginDefinition } from "@tokamaq/sdk";
3
+ import type { uiContributions } from "./contributions.ts";
4
+ import { createHash } from "node:crypto";
5
+ import type { Plugin } from "vite";
6
+
7
+ type GenerateBundle = Extract<NonNullable<Plugin["generateBundle"]>, (...args: never[]) => unknown>;
8
+
9
+ export function artifactBundle(
10
+ contributes: ReturnType<typeof uiContributions>["contributes"],
11
+ plugin: Readonly<PluginDefinition>,
12
+ options: { ui?: false; stripClientSources?: boolean },
13
+ ): GenerateBundle {
14
+ return function (_options, bundle) {
15
+ delete bundle[".tokamaq-backend-entry.js"];
16
+ // Commit the hashes of final emitted bytes, not intermediate compiler
17
+ // inputs. A loader snapshots and verifies these before evaluating code.
18
+ const manifest = artifactManifest(bundle);
19
+ const metadata = JSON.parse(String(manifest.source));
20
+ if (options.ui !== false) {
21
+ const ui = bundle["ui.js"];
22
+ if (!ui || ui.type !== "chunk") throw new Error("Missing plugin UI module");
23
+ if (options.stripClientSources || metadata.entries.local) {
24
+ // Bundlers can refill omitted source text from disk while composing
25
+ // maps. Strip it from the published map before hashing the artifact.
26
+ const asset = bundle["ui.js.map"];
27
+ if (asset?.type === "asset") {
28
+ const map = JSON.parse(String(asset.source));
29
+ stripSourcesContent(map);
30
+ asset.source = JSON.stringify(map);
31
+ }
32
+ if (ui.map) stripSourcesContent(ui.map);
33
+ }
34
+ const depends = { ...plugin.depends };
35
+ const optional = { ...plugin.optional };
36
+ for (const specifier of ui.imports) {
37
+ const match = /^@plugins\/([^/]+)(?:\/ui)?$/.exec(specifier);
38
+ if (match) depends[match[1]!] ??= "*";
39
+ }
40
+ const source = ts.createSourceFile("ui.js", ui.code, ts.ScriptTarget.Latest, true);
41
+ function visit(node: ts.Node) {
42
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
43
+ const arg = node.arguments[0];
44
+ const match = arg && ts.isStringLiteralLike(arg) && /^@plugins\/([^/]+)(?:\/ui)?$/.exec(arg.text);
45
+ if (match && !depends[match[1]!]) optional[match[1]!] ??= "*";
46
+ }
47
+ ts.forEachChild(node, visit);
48
+ }
49
+ visit(source);
50
+ metadata.plugin = definePlugin({
51
+ ...plugin,
52
+ depends,
53
+ optional,
54
+ contributes,
55
+ });
56
+ metadata.entries.ui = {
57
+ code: "ui.js",
58
+ map: "ui.js.map",
59
+ ...(bundle["styles.css"] ? { css: "styles.css" } : {}),
60
+ };
61
+ }
62
+ const hashes = bundleHashes(bundle);
63
+ manifest.source = JSON.stringify({ ...metadata, hashes }, null, 2) + "\n";
64
+ };
65
+ }
66
+
67
+ function bundleHashes(bundle: Parameters<GenerateBundle>[1]) {
68
+ const hashes: Record<string, string> = {};
69
+ for (const [name, file] of Object.entries(bundle)) {
70
+ if (name === "manifest.json") continue;
71
+ hashes[name] = createHash("sha256")
72
+ .update(file.type === "chunk" ? file.code : file.source)
73
+ .digest("hex");
74
+ }
75
+ return hashes;
76
+ }
77
+
78
+ function artifactManifest(bundle: Parameters<GenerateBundle>[1]) {
79
+ const manifest = bundle["manifest.json"];
80
+ if (!manifest || manifest.type !== "asset") throw new Error("Missing artifact manifest");
81
+ return manifest;
82
+ }
83
+
84
+ export function stripSourcesContent(map: { sourcesContent?: unknown }) {
85
+ delete map.sourcesContent;
86
+ }
@@ -0,0 +1,65 @@
1
+ import { checkPluginImports, functionPlacement } from "@tokamaq/sdk/internal/server-build";
2
+ import type { PluginDefinition } from "@tokamaq/sdk";
3
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { readDescriptor } from "./descriptor.ts";
6
+
7
+ const providesSignIn = (provider: { owner?: string; name: string }) =>
8
+ provider.owner === "auth" && provider.name === "method";
9
+
10
+ /** Use the installed artifact identity; installations need not be named after their plugin. */
11
+ export function signInDependency(root: string, plugin: PluginDefinition, catalog?: string) {
12
+ const dependencies = new Set([...Object.keys(plugin.depends ?? {}), ...Object.keys(plugin.optional ?? {})]);
13
+ dependencies.delete("auth");
14
+ if (!dependencies.size) return;
15
+
16
+ const catalogs = new Set([
17
+ catalog && resolve(root, catalog),
18
+ process.env.TOKAMAQ_PLUGIN_DIR,
19
+ dirname(root),
20
+ ]);
21
+ for (const directory of catalogs) {
22
+ if (!directory || !existsSync(directory)) continue;
23
+ const id = installedSignIn(directory, dependencies);
24
+ if (id) return id;
25
+ }
26
+
27
+ return sourceSignIn(root, dependencies);
28
+ }
29
+
30
+ // A sibling source dependency can be identified before its first build.
31
+ function sourceSignIn(root: string, dependencies: Set<string>) {
32
+ for (const id of dependencies) {
33
+ const folder = resolve(dirname(root), id);
34
+ const descriptor = readDescriptor(folder);
35
+ if (descriptor?.id !== id || !(descriptor.depends?.auth || descriptor.optional?.auth)) continue;
36
+ checkPluginImports(folder);
37
+ if (functionPlacement(folder)?.providers.some(providesSignIn)) return id;
38
+ }
39
+ }
40
+
41
+ function installedSignIn(directory: string, dependencies: Set<string>) {
42
+ const folders = readdirSync(directory, { withFileTypes: true })
43
+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
44
+ .map((entry) => resolve(directory, entry.name));
45
+ for (const folder of [directory, ...folders]) {
46
+ const path = ["manifest.json", "dist/manifest.json"]
47
+ .map((name) => resolve(folder, name))
48
+ .find(existsSync);
49
+ if (!path) continue;
50
+ let manifest;
51
+ try {
52
+ manifest = JSON.parse(readFileSync(path, "utf8"));
53
+ } catch {
54
+ continue; // Invalid artifacts are diagnosed by catalog loading.
55
+ }
56
+ const id = manifest?.plugin?.id;
57
+ if (
58
+ typeof id === "string" &&
59
+ dependencies.has(id) &&
60
+ Array.isArray(manifest.contractProviders) &&
61
+ manifest.contractProviders.some(providesSignIn)
62
+ )
63
+ return id;
64
+ }
65
+ }
package/src/build.ts ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env bun
2
+ /** Public artifact build: maintained compilers, one deterministic publisher. */
3
+ import { build } from "vite";
4
+ import { existsSync } from "node:fs";
5
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ import { dirname, resolve } from "node:path";
7
+ import { tokamaq } from "./vite";
8
+
9
+ const args = process.argv.slice(2);
10
+ if (
11
+ args.length > 2 ||
12
+ (args.length === 2 && args[0] !== "--config") ||
13
+ (args[0] === "--config" && args.length !== 2)
14
+ ) {
15
+ throw new Error("Expected [plugin folder] or --config <vite.config.ts>");
16
+ }
17
+ const root = args[0] && args[0] !== "--config" ? resolve(args[0]) : process.cwd();
18
+ const config =
19
+ args[0] === "--config"
20
+ ? resolve(args[1]!)
21
+ : existsSync(resolve(root, "vite.config.ts"))
22
+ ? resolve(root, "vite.config.ts")
23
+ : false;
24
+ let directory: string | undefined;
25
+ const result = await build({
26
+ ...(config ? { configFile: config } : { root, configFile: false }),
27
+ build: { write: false },
28
+ plugins: [
29
+ ...(!config ? [tokamaq()] : []),
30
+ {
31
+ name: "tokamaq-output",
32
+ configResolved(config) {
33
+ if (config.build.write !== false) throw new Error("Generate all output before publishing");
34
+ directory = resolve(config.root, config.build.outDir);
35
+ },
36
+ },
37
+ ],
38
+ });
39
+ if (!directory) throw new Error("Artifact output directory was not resolved");
40
+ const files = (Array.isArray(result) ? result : [result]).flatMap((output) => {
41
+ if (!("output" in output)) throw new Error("Artifact build does not support watch mode");
42
+ return output.output;
43
+ });
44
+ // Manifest last; the M1 installer still needs its own complete-artifact staging.
45
+ files.sort(
46
+ (a, b) =>
47
+ Number(a.fileName === "manifest.json") - Number(b.fileName === "manifest.json") ||
48
+ a.fileName.localeCompare(b.fileName),
49
+ );
50
+ let changed = 0;
51
+ let unchanged = 0;
52
+ for (const file of files) {
53
+ const bytes = Buffer.from(file.type === "chunk" ? file.code : file.source);
54
+ const destination = resolve(directory, file.fileName);
55
+ try {
56
+ if (bytes.equals(await readFile(destination))) {
57
+ unchanged++;
58
+ continue;
59
+ }
60
+ } catch (error) {
61
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
62
+ }
63
+ await mkdir(dirname(destination), { recursive: true });
64
+ const temporary = `${destination}.${process.pid}.tmp`;
65
+ try {
66
+ await writeFile(temporary, bytes);
67
+ await rename(temporary, destination);
68
+ } finally {
69
+ await rm(temporary, { force: true });
70
+ }
71
+ changed++;
72
+ }
73
+ console.log(`Plugin artifact: ${changed} changed, ${unchanged} unchanged`);