Compare commits

...
3 Commits
Author SHA1 Message Date
Clintchiz 1be482caab fix: defer reactive props in branch pre-rendering
Quality / quality (ubuntu-latest) (push) Failing after 10m4s
Quality / quality (windows-latest) (push) Canceled after 0s
2026-08-23 22:51:25 +05:30
Clintchiz 2d1cda0eab chore: restore production release gate 2026-08-23 22:35:11 +05:30
Clintchiz d26403fce2 chore: update public API baseline 2026-08-23 22:24:51 +05:30
17 changed files with 438 additions and 50 deletions
+182 -2
View File
@@ -968,6 +968,7 @@
},
"@wrnexus/cli": {
".": [],
"./test-setup": [],
"./workspace": [
"ResolvedWorkspaceApp",
"ResolvedWorkspaceConfig",
@@ -1352,6 +1353,8 @@
"ActionClientError",
"ActionClientOptions",
"ActionResult",
"ApiClientOptions",
"ApiRequest",
"ClientModuleScope",
"HydrationScopeApi",
"NAV_RUNTIME",
@@ -1365,6 +1368,7 @@
"callServerFunction",
"collectRefs",
"createActionClient",
"createApiClient",
"createOutputProxy",
"createServerProxy",
"getActionRuntime",
@@ -1375,11 +1379,13 @@
"invalidateClientModule",
"invokeOutput",
"loadClientFunctions",
"registerOutputHandler"
"registerOutputHandler",
"useFetch"
]
},
"@wrnexus/db": {
".": [
"AddSeedOptions",
"BaseType",
"Column",
"ColumnDef",
@@ -1390,6 +1396,7 @@
"Dialect",
"Driver",
"ExecResult",
"LedgerOptions",
"Migration",
"MigrationRunOptions",
"MigrationSafetyIssue",
@@ -1406,7 +1413,13 @@
"RelationOptions",
"Repository",
"Row",
"SeedDatabase",
"SeedRow",
"SeedStep",
"SeedUserAccount",
"TxHandle",
"UpsertSeedOptions",
"addSeedData",
"analyzeMigrationSafety",
"analyzeMigrations",
"appliedMigrations",
@@ -1421,6 +1434,8 @@
"cursorPaginate",
"databaseHealth",
"databaseNames",
"defineLedger",
"defineSeed",
"exists",
"firstOrThrow",
"generateQueriesFile",
@@ -1438,15 +1453,20 @@
"queryOperation",
"registerDb",
"registerLazyDb",
"removeSeedData",
"resetDbPerformanceSnapshot",
"retryTransaction",
"rollback",
"runSeedQuery",
"scaffoldMigration",
"seedIfMissing",
"seedUsers",
"setDb",
"softDeleteClause",
"status",
"table",
"tenantScope",
"upsertSeedData",
"v",
"withTransaction"
],
@@ -1647,6 +1667,7 @@
"EncryptionKey",
"EncryptionKeyring",
"ReplayStore",
"SecretResourceOptions",
"createEncryptedRequest",
"createKeyring",
"createMemoryReplayStore",
@@ -1654,6 +1675,7 @@
"decryptEncryptedResponse",
"decryptHttpBody",
"decryptRequest",
"defineSecretResource",
"deriveKey",
"encrypt",
"encryptHttpBody",
@@ -1687,26 +1709,39 @@
"@wrnexus/helpers": {
".": [
"AllowedHosts",
"ApiHandler",
"HttpError",
"LoginRedirectOptions",
"OriginalRequestOptions",
"RequestContext",
"ResourceDefinition",
"ResourceHandlers",
"RetryOptions",
"appOrigin",
"appUrl",
"authorized",
"backoffDelay",
"clamp",
"currentAppName",
"currentAppOrigin",
"defineApiRoute",
"defineResource",
"getOriginalRequestMethod",
"getOriginalRequestOrigin",
"getOriginalRequestPath",
"getOriginalRequestUrl",
"json",
"once",
"redirectToLogin",
"requireJson",
"requireParam",
"requirePermission",
"requireUser",
"retry",
"safeJsonParse",
"sleep",
"stableStringify",
"subjectId",
"withTimeout",
"workspaceAppOrigins",
"workspaceRootDomain"
@@ -1902,6 +1937,25 @@
"isApiReferenceAt"
]
},
"@wrnexus/mail": {
".": [
"MailDriver",
"MailMessage",
"MailOptions",
"MailSandboxDecision",
"MailTemplate",
"SealedMailCredentialsOptions",
"SealedMailDriverOptions",
"defineMail",
"defineMailTemplate",
"defineSealedMailCredentials",
"interpolateTemplate",
"mailSandboxDecision",
"queuedMail",
"sealedMailDriver",
"storedMailTemplate"
]
},
"@wrnexus/mcp": {
".": [
"McpServer",
@@ -1913,6 +1967,20 @@
"runMcpStdio"
]
},
"@wrnexus/metering": {
".": [
"EntitlementPlan",
"EntitlementsOptions",
"MeterKind",
"MeterOptions",
"MeterPack",
"MeterResult",
"MeterStore",
"defineEntitlements",
"defineMeter",
"definePacks"
]
},
"@wrnexus/mobile": {
".": [
"CapacitorBridge",
@@ -2113,6 +2181,70 @@
"traceMiddleware"
]
},
"@wrnexus/payment": {
".": [
"CreateIntentInput",
"CustomerInput",
"GatewayCapabilities",
"GatewayContractFixture",
"GatewayContractReport",
"GatewayIntent",
"GatewayMethod",
"GatewayRefund",
"GatewaySupport",
"InitializePaymentInput",
"Money",
"PayPalConfig",
"PaymentEvent",
"PaymentGateway",
"PaymentIntent",
"PaymentMethod",
"PaymentOptions",
"PaymentRefund",
"PaymentResult",
"PaymentService",
"PaymentStatus",
"PaymentStore",
"RazorpayConfig",
"RefundInput",
"SandboxOptions",
"StripeConfig",
"WebhookEvent",
"configurePayment",
"databasePaymentStore",
"defineGateway",
"definePayment",
"derivePaymentStatus",
"exerciseGatewayContract",
"getPaymentService",
"memoryPaymentStore",
"paymentPlugin",
"paypalGateway",
"razorpayGateway",
"sandboxGateway",
"signSandboxWebhook",
"stripeGateway",
"verifyGatewayContract"
],
"./adapters": [
"PayPalConfig",
"RazorpayConfig",
"SandboxOptions",
"StripeConfig",
"paypalGateway",
"razorpayGateway",
"sandboxGateway",
"signSandboxWebhook",
"stripeGateway"
],
"./plugin": [
"default",
"paymentPlugin"
],
"./runtime-webhook": [
"POST"
]
},
"@wrnexus/playground": {
".": [
"PlaygroundCompilation",
@@ -2277,21 +2409,41 @@
"@wrnexus/queue": {
".": [
"AddOptions",
"DefineQueueOptions",
"DefinedJob",
"DefinedJobOptions",
"DefinedJobs",
"DefinedQueue",
"DurableQueue",
"DurableQueueOptions",
"Job",
"JobContext",
"JobDefinition",
"JobHandler",
"JobStateMachineOptions",
"JobStatus",
"OutboxEntry",
"OutboxWriter",
"POSTGRES_QUEUE_SCHEMA",
"Queue",
"QueueAdminOptions",
"QueueDashboardSnapshot",
"QueueEvent",
"QueueEventType",
"QueueHealth",
"QueueJobDefinitions",
"QueueJobRecord",
"QueueJobState",
"QueueOptions",
"QueueScheduler",
"QueueStorage",
"QueueStorageConfig",
"QueueStore",
"RedisQueueClient",
"SagaStep",
"ScheduledJob",
"SqlQueueClient",
"SqliteQueueClient",
"SubjectJob",
"SubjectQueue",
"WorkerDefinition",
@@ -2303,24 +2455,46 @@
"WorkflowStep",
"WorkflowStore",
"addBatch",
"configureQueueStorage",
"configuredQueueStore",
"createDurableQueue",
"createQueue",
"createQueueAdminHandler",
"createQueueScheduler",
"createWorkflowEngine",
"cronToInterval",
"databaseQueueStore",
"defineDurableWorkflow",
"defineJob",
"defineJobStateMachine",
"defineQueue",
"defineSaga",
"defineWorker",
"defineWorkflow",
"drainOutbox",
"installDatabaseQueueSchema",
"installOutboxSchema",
"installSqliteQueueSchema",
"memoryQueueStore",
"memoryWorkflowStore",
"postgresQueueStore",
"queueDashboardSnapshot",
"queueStorageConfig",
"redisQueueStore",
"renderQueueDashboard",
"runQueueDaemon",
"runWorker",
"subjectQueue"
"sqliteQueueSchema",
"sqliteQueueStore",
"subjectQueue",
"testQueue",
"withOutbox"
],
"./sqlite": [
"SqliteQueueClient",
"installSqliteQueueSchema",
"sqliteQueueSchema",
"sqliteQueueStore"
]
},
"@wrnexus/react": {
@@ -2363,6 +2537,7 @@
".": [
"AnimationTimeline",
"Cleanup",
"FormState",
"HistorySignal",
"ReactiveContext",
"ReactiveScope",
@@ -2389,6 +2564,7 @@
"transition",
"untrack",
"urlSignal",
"useForm",
"watch"
]
},
@@ -2916,11 +3092,14 @@
".": [
"BrowserArtifactPage",
"Deferred",
"DetectMutationsOptions",
"FetchMock",
"Harness",
"HarnessOptions",
"JsonResponse",
"MemoryCookieJar",
"MutationCase",
"MutationReport",
"TestRequestOptions",
"TransactionalDatabase",
"WaitForOptions",
@@ -2938,6 +3117,7 @@
"createTestContext",
"deferred",
"describe",
"detectMutations",
"expect",
"expectProblem",
"it",
+50 -13
View File
@@ -1,6 +1,6 @@
"use strict";
// Generated by scripts/build-editor-compiler.mjs. Do not edit directly.
// WRN editor compiler source hash: 1e7593d6b6bd1c9b8439fc34a30f9db9f7ae64f1788365a74115170aa34cd185
// WRN editor compiler source hash: 884c9faffb5517c907321484014e00562654ea0ba96e432bec319e0001934446
// WRN editor compiler generator hash: a54ca847c758bc98d8e353ad6d70088df31de1820f6cf9d1c3462505f563e6b8
// Generated with TypeScript: 6.0.3
const __nodeRequire = require;
@@ -1148,6 +1148,31 @@ function componentEventAttribute(name) {
}
return `data-wrn-out-${name}`;
}
/** Expand bind:value/bind:checked into a reactive prop plus assignment handler. */
function expandBindings(attrs) {
const output = [];
for (const attr of attrs) {
if (attr.event || !attr.name.startsWith("bind:")) {
output.push(attr);
continue;
}
const target = attr.name.slice("bind:".length);
if (target !== "value" && target !== "checked") {
throw new Error(`Unknown .wrn binding '${attr.name}'. Use bind:value or bind:checked.`);
}
const expression = wholeAttributeExpression(attr.value) ?? attr.value.trim();
if (!/^[A-Za-z_$][\w$]*$/.test(expression)) {
throw new Error(`${attr.name} requires a writable state name, received '${expression}'.`);
}
output.push({ name: target, value: `{${expression}}`, event: false });
output.push({
name: target === "checked" ? "change" : "input",
value: `${expression} = payload.${target}`,
event: true,
});
}
return output;
}
function reactiveAttrValue(raw, reactive) {
let found = false;
const value = raw.replace(/\{([^{}]+)\}/g, (whole, inner) => {
@@ -1166,6 +1191,7 @@ function reactiveAttrValue(raw, reactive) {
return found ? value : null;
}
function renderAttrs(attrs, csrId, reactive = null, dynamicExpressions) {
attrs = expandBindings(attrs);
let bindIndex = 0;
const rendered = attrs
.map((attr) => {
@@ -1302,7 +1328,7 @@ function renderLoopBody(node, locals = []) {
return compileIfExpr(node, locals);
}
const componentTag = isComponentTag(node.tag);
const attrs = node.attrs
const attrs = expandBindings(node.attrs)
.filter((attr) => attr.name !== "data-component")
.map((attr) => {
const name = attr.event
@@ -1562,9 +1588,9 @@ function renderPageComponentInvocation(node, ssrBindings, csrBindings, apiBindin
const island = islandMarkerFor(node);
if (island)
return island;
const attrs = node.attrs
const attrs = expandBindings(node.attrs)
.filter((attr) => attr.name !== "data-component")
.map((attr) => renderPageComponentAttr(attr, loops))
.map((attr) => renderPageComponentAttr(attr, loops, reactive))
.join("");
const inner = node.children
.map((child) => renderNode(child, ssrBindings, csrBindings, apiBindings, loops, reactive))
@@ -1577,7 +1603,7 @@ function renderNestedComponentInvocation(node, ctx) {
if (island)
return island;
let bindIndex = 0;
const attrs = node.attrs
const attrs = expandBindings(node.attrs)
.filter((attr) => attr.name !== "data-component")
.map((attr) => {
const spread = /^\{\.\.\.([A-Za-z_$][\w$]*)\}$/.exec(attr.name);
@@ -2446,6 +2472,8 @@ ${exposed
${declarations}
${visible.length
? ` const __values = await Promise.all([${visible.map((entry) => `__load_${entry.name}()`).join(", ")}]);
const __response = __values.find((value) => value instanceof Response);
if (__response) return __response;
return { ${visible.map((entry, index) => `${JSON.stringify(entry.name)}: __values[${index}]`).join(", ")} };`
: ""}
}`;
@@ -2765,7 +2793,7 @@ function renderClientControlTemplate(nodes) {
}
const componentTag = isComponentTag(node.tag);
let bindIndex = 0;
const attrs = node.attrs
const attrs = expandBindings(node.attrs)
.map((attribute) => {
const name = attribute.event
? componentTag
@@ -2803,19 +2831,21 @@ function encodeClientControl(value) {
}
function renderComponentIfNode(node, ctx) {
let expression = "``";
const clientBranches = [];
for (let index = node.branches.length - 1; index >= 0; index--) {
const branch = node.branches[index];
const body = branch.body.map((child) => renderComponentNode(child, ctx)).join("");
const bodyExpression = "`" + body + "`";
clientBranches.unshift(`{ cond: ${branch.cond === null ? "null" : JSON.stringify(branch.cond)}, body: ${bodyExpression} }`);
expression =
branch.cond === null
? bodyExpression
: `(${ctx.resolveExpr(branch.cond)}) ? ${bodyExpression} : ${expression}`;
}
const definition = encodeClientControl(node.branches.map((branch) => ({
cond: branch.cond,
body: renderClientControlTemplate(branch.body),
})));
// Render all branches on the server into an inert, encoded definition.
// A branch first selected in the browser therefore contains the real nested
// component HTML and scope metadata, not a data-component placeholder.
const definition = `\${__wrnexusEncodeControl([${clientBranches.join(",")}])}`;
return `<template data-wrn-if="${definition}"></template>${"${" + expression + "}"}<template data-wrn-control-end></template>`;
}
function renderComponentEachNode(node, ctx) {
@@ -2955,7 +2985,7 @@ function renderComponentNode(node, ctx) {
}
}
const isExplicitComponentMount = node.attrs.some((attribute) => attribute.name === "data-component");
const attrs = node.attrs
const attrs = expandBindings(node.attrs)
.filter((a) => a.name !== "class" && !a.name.startsWith("class:"))
.map((a) => {
const spread = /^\{\.\.\.([A-Za-z_$][\w$]*)\}$/.exec(a.name);
@@ -3413,6 +3443,9 @@ function __wrnRaw(v: unknown): string {
}`);
}
if (needsScope) {
out.push(`function __wrnexusEncodeControl(value: unknown): string {
return __WrnexusBuffer.from(JSON.stringify(value), "utf8").toString("base64");
}`);
out.push(`function __wrnexusSerializeScopeValue(value: unknown): string {
if (value === undefined) {
return "undefined";
@@ -3495,7 +3528,7 @@ function __wrnProp(v) {
const value = v !== null && typeof v === "object" ? JSON.stringify(v) : String(v == null ? "" : v);
return __wrnAttr(value);
}
function renderPageComponentAttr(attr, dynamicExpressions) {
function renderPageComponentAttr(attr, dynamicExpressions, _reactive) {
if (attr.event) {
return ` ${componentEventAttribute(attr.name)}="${attrEscape(attr.value)}"`;
}
@@ -3508,7 +3541,11 @@ function renderPageComponentAttr(attr, dynamicExpressions) {
}
dynamicExpressions.push(`\${__wrnexusPropAttr(${expression})}`);
const marker = `\x00WRNEACH${dynamicExpressions.length - 1}\x00`;
return ` ${attr.name}="${marker}"`;
// The mount disappears during SSR. Preserve every dynamic component prop
// as a parent-owned binding; server-only expressions simply fail closed in
// the browser, while page state can continue driving the mounted child.
const binding = ` data-wrn-prop-bind-${dynamicExpressions.length - 1}="${attrEscape(JSON.stringify([attr.name, attr.value]))}"`;
return ` ${attr.name}="${marker}"${binding}`;
}
},
+1 -1
View File
@@ -1,4 +1,4 @@
// WRN editor extension source hash: 7fd27405852b02ce3f64e8b7cc08e84029aca9f5505217caafe56be8d3ca4931
// WRN editor extension source hash: 20e8ecae36b610b418104c3bfd7f25326dd7ad85a0822416b8245107819f7ed2
// WRN editor extension generator hash: 456d1d614e44e5fb1f19b784176c09cf2ade9b64ef73a17934c2698150b62728
"use strict";
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
+48 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env node
// WRN editor language server source hash: 3c6060ff9db332cf1dc01a467d795fb2d002300400072a4b87437c48d61ab7f9
// WRN editor language server source hash: 7d485053c38631885fd8d53d84d92f0ef02893d99d0f6c0553d6839971dd7ac5
// WRN editor language server generator hash: f593a44aaf05495b789ce7a3086bee1eebb951b884d41c0e017bbcfe5f547e72
// @bun @bun-cjs
(function(exports, require, module, __filename, __dirname) {var __create = Object.create;
@@ -173103,6 +173103,7 @@ function virtualTypeScriptModule(source, filePath = "component.wrn", appRoot = f
append(`declare const api: { ${apiType} };`);
append(`declare const props: Readonly<${ast.name}Props>;`);
append("declare const refs: Record<string, Element | null>;");
append("declare function useFetch(path: string, method?: string | { method?: string; query?: unknown; params?: unknown; body?: unknown; data?: unknown }, input?: unknown): Promise<any>;");
append(ast.kind === "global-store" || ast.kind === "page-store" ? storeContract(ast) : componentContract(ast));
append(importedWrnDeclarations(ast, filePath, appRoot));
const sharedNames = new Set(ast.runtimeFunctions.filter((fn) => fn.runtime === "shared").map((fn) => fn.name));
@@ -173119,6 +173120,49 @@ ${sharedAliases}`);
append(functionDeclaration(fn), fn.source);
append("}");
}
const viewFunctions = new Map;
for (const fn of ast.runtimeFunctions) {
if (fn.runtime !== "server")
viewFunctions.set(fn.name, fn.runtime);
}
for (const [name, runtime] of viewFunctions) {
append(`declare const ${name}: typeof ${runtimeNamespace(runtime)}.${name};`);
}
let bindingIndex = 0;
const appendViewBindings = (nodes, locals) => {
for (const node of nodes) {
if (node.type === "element") {
for (const attr of node.attrs) {
const expressions = attr.event ? [attr.value] : [...attr.value.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1].trim());
for (const expression of expressions) {
if (!expression.trim())
continue;
const declarations = [
...[...locals].map((name) => `declare const ${name}: any;`),
...attr.event ? ["declare const payload: any;", "declare const event: Event;"] : []
].join(" ");
append(`namespace __wrn_view_${bindingIndex++} { ${declarations} void (${expression}); }`, attr.value);
}
}
appendViewBindings(node.children, locals);
} else if (node.type === "if") {
for (const branch of node.branches) {
if (branch.cond)
append(`namespace __wrn_view_${bindingIndex++} { void (${branch.cond}); }`, branch.cond);
appendViewBindings(branch.body, locals);
}
} else if (node.type === "each") {
append(`namespace __wrn_view_${bindingIndex++} { void (${node.list}); }`, node.list);
const nested = new Set(locals);
nested.add(node.item);
if (node.index)
nested.add(node.index);
appendViewBindings(node.body, nested);
appendViewBindings(node.empty, locals);
}
}
};
appendViewBindings(ast.view, new Set);
return {
ast,
fileName: filePath.replace(/\.wrn$/i, ".wrn.ts"),
@@ -173224,7 +173268,7 @@ function componentUsageDiagnostics(source, ast, filePath, appRoot) {
const shape = shapes.get(node.tag);
if (!shape)
return;
const attributes = new Map(node.attrs.filter((attr) => !attr.event).map((attr) => [attr.name, attr]));
const attributes = new Map(node.attrs.filter((attr) => !attr.event).map((attr) => [attr.name.startsWith("bind:") ? attr.name.slice(5) : attr.name, attr]));
const outputNames = new Set(shape.outputs.map((output) => output.name));
const position = lineAt(source, `<${node.tag}`);
for (const prop of shape.props) {
@@ -173261,7 +173305,8 @@ function componentUsageDiagnostics(source, ast, filePath, appRoot) {
}
if (/^(?:class|id|style|slot|data-|aria-)/.test(attr.name) || attr.name === "attrs")
continue;
const prop = known.get(attr.name);
const propName = attr.name.startsWith("bind:") ? attr.name.slice(5) : attr.name;
const prop = known.get(propName);
if (!prop) {
diagnostics.push({
code: "WRN-COMPONENT-UNKNOWN-PROP",
+3 -1
View File
@@ -72,7 +72,9 @@ export function createTestPlan(appRoot: string, args: string[]): TestCommandPlan
const watch = args.includes("--watch");
const profile = args.find((value) => value.startsWith("--profile="))?.slice(10) || "test";
const setupSource = join(import.meta.dir, "test-setup.ts");
const setupModule = existsSync(setupSource) ? setupSource : join(import.meta.dir, "test-setup.js");
const setupModule = existsSync(setupSource)
? setupSource
: join(import.meta.dir, "test-setup.js");
const shard = args.find((value) => value.startsWith("--shard="))?.slice(8);
const browsers = (args.find((value) => value.startsWith("--browsers="))?.slice(11) ?? "chromium")
.split(",")
+1 -1
View File
@@ -3175,7 +3175,7 @@ function __wrnProp(v: unknown): string {
function renderPageComponentAttr(
attr: Attr,
dynamicExpressions: string[],
reactive: PageReactive | null,
_reactive: PageReactive | null,
): string {
if (attr.event) {
return ` ${componentEventAttribute(attr.name)}="${attrEscape(attr.value)}"`;
+11 -3
View File
@@ -15,9 +15,17 @@ function fakeDb() {
test("seed helpers parameterize object rows and removals", async () => {
const { db, calls } = fakeDb();
await addSeedData(db, [{ code: "free", credits: 10 }, { code: "pro", credits: 20 }], "plans", {
conflict: "ignore",
});
await addSeedData(
db,
[
{ code: "free", credits: 10 },
{ code: "pro", credits: 20 },
],
"plans",
{
conflict: "ignore",
},
);
await removeSeedData(db, { code: "free" }, "plans");
expect(calls[0]).toEqual({
sql: "INSERT OR IGNORE INTO plans (code, credits) VALUES (?, ?)",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@wrnexus/dev-server",
"version": "0.8.52",
"version": "0.8.53",
"type": "module",
"main": "src/index.ts",
"exports": {
+19 -2
View File
@@ -1739,6 +1739,15 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
// Props may carry `{t:key}` i18n markers — resolve them for the active
// language before handing them to the component.
const props = resolveTProps(parseComponentProps(attrStr!), translate);
// Client control templates retain reactive expressions (for example
// `metrics="{metrics}"`) because their parent state is not available
// while we pre-render the inert branch metadata. Do not feed those
// expression strings into typed component coercion. Rendering with the
// component defaults creates the real child boundary; the bridged prop
// binding synchronizes the live value when the branch is instantiated.
for (const [key, value] of Object.entries(props)) {
if (/^\{[\s\S]*\}$/.test(value) && !/^\{t:/.test(value)) delete props[key];
}
if (normalizedName === "languageswitcher" && deps.i18n) {
props.locales ??= JSON.stringify(
deps.i18n.langs.map((locale) => ({
@@ -1777,7 +1786,10 @@ export function createHandlers(deps: RuntimeDeps): Handlers {
(match) => ` ${match[1]}`,
).join("");
const bridged = propBindings
? rendered.replace(/(<[A-Za-z][A-Za-z0-9-]*\b[^>]*\bdata-scope="[^"]*")/, `$1${propBindings}`)
? rendered.replace(
/(<[A-Za-z][A-Za-z0-9-]*\b[^>]*\bdata-scope="[^"]*")/,
`$1${propBindings}`,
)
: rendered;
result += await renderComponents(bridged, translate, language, depth + 1);
} catch (err) {
@@ -2679,7 +2691,12 @@ export function parseComponentProps(attrStr: string): Record<string, string> {
const props: Record<string, string> = {};
for (const m of attrStr.matchAll(/([A-Za-z_][\w-]*)(?:="([^"]*)")?/g)) {
const key = m[1]!;
if (key === "data-component") continue;
if (
key === "data-component" ||
key.startsWith("data-wrn-bind-") ||
key.startsWith("data-wrn-prop-bind-")
)
continue;
props[key] = decodeHtmlEntities(m[2] ?? "");
}
return props;
@@ -90,6 +90,58 @@ test("a component in an initially hidden client branch is server-prepared for in
expect(branches[0].body).not.toContain("data-component=");
});
test("typed components in client branches use defaults until reactive props are available", async () => {
const root = mkdtempSync(join(tmpdir(), "wrnexus-component-reactive-branch-"));
roots.push(root);
const app = join(root, "app");
mkdirSync(join(app, "pages"), { recursive: true });
mkdirSync(join(app, "components"), { recursive: true });
writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");
writeFileSync(join(app, "components/Panel.wrn"), "component Panel { view { <section /> } }\n");
const marker = "[&quot;items&quot;,&quot;{items}&quot;]";
const definition = Buffer.from(
JSON.stringify([
{
cond: "open",
body: `<div data-component="Panel" items="{items}" visible="{true}" data-wrn-prop-bind-0="${marker}"></div>`,
},
]),
"utf8",
).toString("base64");
let observed: Record<string, string> | undefined;
const handlers = createHandlers({
mode: "development",
hmr: false,
router: buildRouter(app),
loadModule: async (file) =>
basename(file) === "Panel.wrn"
? {
render: (props: Record<string, string>) => {
observed = props;
return '<section data-scope="items: [], visible: false" data-wrn-scope="e30="></section>';
},
}
: {
default: () =>
`<template data-wrn-if="${definition}"></template><template data-wrn-control-end></template>`,
},
getMiddleware: async () => [],
assets: { serve: async () => null },
} satisfies RuntimeDeps);
const response = await handlers.fetch(new Request("https://example.test/"), {
upgrade: () => false,
});
const html = await response!.text();
expect(observed).toEqual({});
const encoded = /data-wrn-if="([A-Za-z0-9+/=]+)"/.exec(html)?.[1];
const branches = JSON.parse(Buffer.from(encoded!, "base64").toString("utf8"));
expect(branches[0].body).toContain("<section");
expect(branches[0].body).toContain("data-wrn-prop-bind-0");
expect(branches[0].body).not.toContain("data-component=");
});
test("SSR carries a parent prop binding onto the rendered child scope", async () => {
const root = mkdtempSync(join(tmpdir(), "wrnexus-component-prop-"));
roots.push(root);
@@ -97,7 +149,10 @@ test("SSR carries a parent prop binding onto the rendered child scope", async ()
mkdirSync(join(app, "pages"), { recursive: true });
mkdirSync(join(app, "components"), { recursive: true });
writeFileSync(join(app, "pages/index.ts"), "export default () => '';\n");
writeFileSync(join(app, "components/Child.wrn"), "component Child { props { value = 0 } view { <b>{value}</b> } }\n");
writeFileSync(
join(app, "components/Child.wrn"),
"component Child { props { value = 0 } view { <b>{value}</b> } }\n",
);
const marker = "[&quot;value&quot;,&quot;{count}&quot;]";
const handlers = createHandlers({
mode: "development",
@@ -106,11 +161,16 @@ test("SSR carries a parent prop binding onto the rendered child scope", async ()
loadModule: async (file) =>
basename(file) === "Child.wrn"
? { render: () => '<div data-scope="value: 1" data-wrn-scope="e30="><b>1</b></div>' }
: { default: () => `<div data-component="Child" value="1" data-wrn-prop-bind-0="${marker}"></div>` },
: {
default: () =>
`<div data-component="Child" value="1" data-wrn-prop-bind-0="${marker}"></div>`,
},
getMiddleware: async () => [],
assets: { serve: async () => null },
} satisfies RuntimeDeps);
const response = await handlers.fetch(new Request("https://example.test/"), { upgrade: () => false });
const response = await handlers.fetch(new Request("https://example.test/"), {
upgrade: () => false,
});
const html = await response!.text();
expect(html).toContain(`data-wrn-prop-bind-0="${marker}"`);
expect(html).not.toContain('data-component="Child"');
+1 -1
View File
@@ -117,7 +117,7 @@ export function defineSealedMailCredentials(options: SealedMailCredentialsOption
const secret = process.env[env];
if (!secret)
throw new Error(`${env} is not set; it is required to seal mail credentials at rest.`);
let length = 0;
let length: number;
try {
length = atob(secret).length;
} catch {
+40
View File
@@ -0,0 +1,40 @@
# @wrnexus/metering
Framework-native entitlement catalogs, credit packs, and usage metering for WrNexus applications.
The package keeps policy separate from persistence: applications provide a `MeterStore`, while the metering facade validates unit amounts and reports insufficient balances separately from storage faults. All amounts are positive safe integers except explicit adjustments, which may be positive or negative but never zero.
## Usage
```ts
import { defineEntitlements, defineMeter, definePacks } from "@wrnexus/metering";
const entitlements = defineEntitlements({
plans: () => [
{ code: "free", name: "Free", features: [], allowance: 10 },
{ code: "pro", name: "Pro", features: ["exports"], allowance: 1_000 },
],
subscriptionFor: async (subjectId) => subscriptions.planFor(subjectId),
fallback: "free",
});
const packs = definePacks([
{ code: "starter", units: 100 },
{ code: "plus", units: 500 },
]);
const meter = defineMeter({ store });
if (await entitlements.enabled("user-1", "exports")) {
const result = await meter.reserve("user-1", 1, "export report");
if (!result.ok) console.error(result.reason);
}
```
## API
- `defineEntitlements(options)` resolves a subject's plan, features, and allowance from a server-owned catalog, with an explicit fallback plan.
- `definePacks(entries)` creates an immutable, prototype-safe lookup of purchasable unit packs. Clients select a pack code rather than supplying an amount.
- `defineMeter(options)` exposes `balance`, `reserve`, `grant`, `purchase`, `refund`, and `adjust` operations over an application-provided store.
Meter operations return `{ ok: true }` on success or `{ ok: false, reason, fault? }` on refusal. A result with `fault: true` identifies an underlying storage error; use `onFault` for operational reporting without exposing exception-based control flow to callers.
+8 -8
View File
@@ -37,15 +37,15 @@ function createQueue(options?: QueueOptions): Queue;
#### `QueueOptions`
| Option | Type | Default | Description |
| ------------- | ------------------------------------ | ---------- | -------------------------------------------------------- |
| `maxAttempts` | `number` | `3` | Default max attempts per job before it is dead-lettered. |
| `backoffMs` | `number` | `1000` | Base retry backoff in ms; doubles per attempt. |
| `pollMs` | `number` | `250` | Poll interval used once `start()` is called (ms). |
| `onFailed` | `(job: Job, error: unknown) => void` | — | Called when a job exhausts its attempts. |
| `concurrency` | `number` | unlimited | Maximum jobs claimed by one `drain()` call. |
| Option | Type | Default | Description |
| ------------- | ------------------------------------ | ---------- | --------------------------------------------------------------------------------------- |
| `maxAttempts` | `number` | `3` | Default max attempts per job before it is dead-lettered. |
| `backoffMs` | `number` | `1000` | Base retry backoff in ms; doubles per attempt. |
| `pollMs` | `number` | `250` | Poll interval used once `start()` is called (ms). |
| `onFailed` | `(job: Job, error: unknown) => void` | — | Called when a job exhausts its attempts. |
| `concurrency` | `number` | unlimited | Maximum jobs claimed by one `drain()` call. |
| `capacity` | `number` | unlimited | Optional maximum queued jobs; omitted queues never scan merely to enforce a hidden cap. |
| `now` | `() => number` | `Date.now` | Clock injection for deterministic tests. |
| `now` | `() => number` | `Date.now` | Clock injection for deterministic tests. |
### `Queue`
+1 -5
View File
@@ -206,8 +206,4 @@ export type {
export { withDatabaseRollback, createFactory, captureBrowserArtifacts } from "./platform.ts";
export type { TransactionalDatabase, BrowserArtifactPage } from "./platform.ts";
export { detectMutations } from "./mutation.ts";
export type {
MutationCase,
MutationReport,
DetectMutationsOptions,
} from "./mutation.ts";
export type { MutationCase, MutationReport, DetectMutationsOptions } from "./mutation.ts";
+3 -4
View File
@@ -43,10 +43,9 @@ export async function detectMutations<T, O>(
(same ? survived : killed).push(mutation.name);
}
if (survived.length) {
throw Object.assign(
new Error(`WRN-MUTATION-SURVIVED: ${survived.join(", ")}`),
{ report: { baseline, killed, survived } },
);
throw Object.assign(new Error(`WRN-MUTATION-SURVIVED: ${survived.join(", ")}`), {
report: { baseline, killed, survived },
});
}
return { baseline, killed, survived };
}
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { checkWrnSource } from "../src/index.ts";
+5 -1
View File
@@ -191,7 +191,11 @@ const runtimeBudgets = {
// buys a correctness fix, not a feature. The encoder was trimmed to the
// btoa/encodeURIComponent idiom first, which recovered 65 of those bytes;
// what remains is the smallest form that still handles non-ASCII.
"reactive-runtime.ts": 51_600,
// Raised to 52_000 on 2026-08-23 after the reviewed callApi transport and
// loop-locals runtime landed together at 51,926 bytes under the pinned Bun
// 1.3.14 production minifier. This preserves a narrow 74-byte ceiling rather
// than masking the shipped feature cost with a broad allowance.
"reactive-runtime.ts": 52_000,
"component-controllers.ts": 24_100,
"nav-runtime.ts": 12_000,
"realtime-runtime.ts": 8_000,