@pwfabric/compiler 0.0.0-stage → 1.0.0-rc.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.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Entry wrappers — the thin module the compiler actually bundles.
3
+ *
4
+ * Which template applies is decided by the kind's `entry` metadata in
5
+ * `@pwfabric/contracts` (`atomKindMeta(kind).entry`), not by
6
+ * ad-hoc "block vs capability vs connector" branches:
7
+ *
8
+ * - block (identity) → re-export the component and the definition under
9
+ * the stable names `Component` + `definition`, so the
10
+ * runtime's block module loader reads two fixed keys
11
+ * whatever the author named them.
12
+ * - capability (identity) → opaque `export *` (the handler contract is not
13
+ * normalised).
14
+ * - connector (sibling) → loader-contract adapter: `createConnector` that
15
+ * delegates to an explicit export, wraps an engine
16
+ * class (`prototype.query`), or calls/constructs the
17
+ * default export of the sibling `./<Name>`.
18
+ * - provider (sibling) → per-facet entry over the SHARED vendor motor
19
+ * (`../index`): binds the domain's entity map from
20
+ * `./<domain>` into the vendor engine class, or falls
21
+ * back to a vendor `create*` factory.
22
+ *
23
+ * @module @pwfabric/compiler/wrappers
24
+ */
25
+ import { atomKindMeta } from '@pwfabric/contracts';
26
+ /**
27
+ * NAMES ARE UNTRUSTED. `engineName` and `sourceBase` come from pack folder and
28
+ * file names, and they are written into generated SOURCE — a name carrying a
29
+ * quote, a newline or `'; …; //` would be code that no screen ever looked at.
30
+ * Two defences, both always on: the name must match a strict pattern (checked
31
+ * here and, as a diagnostic, by `compileAtom` before it gets this far), and
32
+ * every specifier, property key and message built from a name is emitted
33
+ * through `JSON.stringify`, never spliced between hand-written quotes.
34
+ */
35
+ const ENGINE_NAME_RE = /^[A-Za-z0-9_-]+$/;
36
+ const SOURCE_BASE_RE = /^[A-Za-z0-9_.-]+$/;
37
+ /** Connector `<Name>` / provider `<domain>`: letters, digits, `_`, `-`. */
38
+ export function isValidEngineName(name) {
39
+ return ENGINE_NAME_RE.test(name);
40
+ }
41
+ /** Entry basename without extension: letters, digits, `_`, `-`, `.` — never `..`. */
42
+ export function isValidSourceBase(base) {
43
+ return SOURCE_BASE_RE.test(base) && !base.includes('..') && base !== '.';
44
+ }
45
+ /**
46
+ * The single wrapper registry, keyed off the kind's contract metadata.
47
+ * Throws on a name that fails {@link isValidEngineName} / {@link isValidSourceBase}.
48
+ */
49
+ export function buildWrapperSource(kind, ctx) {
50
+ const meta = atomKindMeta(kind);
51
+ if (meta.entry === 'sibling-generated') {
52
+ const name = ctx.engineName ?? '';
53
+ if (!isValidEngineName(name))
54
+ throw new Error(`invalid engine name ${JSON.stringify(name)}`);
55
+ return kind === 'provider' ? providerEntrySource(name) : connectorEntrySource(name);
56
+ }
57
+ // identity
58
+ const sourceBase = ctx.sourceBase ?? '';
59
+ if (!isValidSourceBase(sourceBase))
60
+ throw new Error(`invalid entry basename ${JSON.stringify(sourceBase)}`);
61
+ if (kind === 'block') {
62
+ return `import * as _atom from ${JSON.stringify(`./${sourceBase}.js`)}
63
+
64
+ const _isDef = (v) =>
65
+ v != null && typeof v === 'object' && 'type' in v && 'schema' in v
66
+
67
+ const _resolveDefinition = (m) => {
68
+ for (const k of Object.keys(m)) {
69
+ const v = m[k]
70
+ if (_isDef(v)) return v
71
+ }
72
+ return null
73
+ }
74
+
75
+ const _resolveComponent = (m) => {
76
+ if (typeof m.default === 'function') return m.default
77
+ for (const k of Object.keys(m)) {
78
+ const v = m[k]
79
+ if (typeof v === 'function') return v
80
+ }
81
+ return null
82
+ }
83
+
84
+ export const definition = _resolveDefinition(_atom)
85
+ export const Component = _resolveComponent(_atom)
86
+ `;
87
+ }
88
+ // capability + any other identity kind
89
+ return `export * from ${JSON.stringify(`./${sourceBase}.js`)}\n`;
90
+ }
91
+ // ── sibling-generated engine adapters ──
92
+ const SHARED_ENGINE_HELPERS = `
93
+ const _isEngineClass = (v: unknown): boolean =>
94
+ typeof v === 'function' &&
95
+ !!(v as { prototype?: { query?: unknown } }).prototype &&
96
+ typeof (v as { prototype: { query?: unknown } }).prototype.query === 'function'
97
+ `;
98
+ /**
99
+ * Wrapper for kind='connector' — adapts `connectors/<Name>.ts` to the loader
100
+ * contract. Priority: explicit `createConnector` export → engine class
101
+ * (`prototype.query`) → default export (called or constructed).
102
+ */
103
+ function connectorEntrySource(name) {
104
+ return `// AUTO-GENERATED (pwfabric-compiler) — loader-contract adapter.
105
+ import * as _mod from ${JSON.stringify(`./${name}`)}
106
+ ${SHARED_ENGINE_HELPERS}
107
+ export function createConnector(
108
+ getAccessToken: () => Promise<string | null>,
109
+ config: Record<string, unknown>
110
+ ): unknown {
111
+ const m = _mod as Record<string, unknown>
112
+ const direct = m['createConnector']
113
+ if (typeof direct === 'function' && !_isEngineClass(direct)) {
114
+ return (direct as (t: unknown, c: unknown) => unknown)(getAccessToken, config)
115
+ }
116
+ for (const k of Object.keys(m)) {
117
+ const v = m[k]
118
+ if (_isEngineClass(v)) {
119
+ return new (v as new (t: unknown, c: unknown) => unknown)(getAccessToken, config)
120
+ }
121
+ }
122
+ const d = m['default']
123
+ if (typeof d === 'function') {
124
+ return _isEngineClass(d)
125
+ ? new (d as new (t: unknown, c: unknown) => unknown)(getAccessToken, config)
126
+ : (d as (t: unknown, c: unknown) => unknown)(getAccessToken, config)
127
+ }
128
+ throw new Error(
129
+ ${JSON.stringify(`connector module "${name}" exports no engine (createConnector / class with query() / default)`)}
130
+ )
131
+ }
132
+ export default createConnector
133
+ `;
134
+ }
135
+ /**
136
+ * Wrapper for kind='provider' — thin per-facet entry over the SHARED vendor
137
+ * motor. Binds the domain: the entity module's EntityMap + the vendor index's
138
+ * engine class (`new Engine(getAccessToken, domainMap)`). Falls back to a
139
+ * vendor-level `create*` factory (all-domain engine) when no engine class is
140
+ * exported.
141
+ */
142
+ function providerEntrySource(domain) {
143
+ return `// AUTO-GENERATED (pwfabric-compiler) — per-facet engine entry.
144
+ import * as _vendor from '../index'
145
+ import * as _domain from ${JSON.stringify(`./${domain}`)}
146
+ ${SHARED_ENGINE_HELPERS}
147
+ const _isEntityMap = (v: unknown): boolean => {
148
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return false
149
+ const vals = Object.values(v as Record<string, unknown>)
150
+ return vals.length > 0 && vals.every((x) => !!x && typeof x === 'object')
151
+ }
152
+
153
+ const _domainMap = (() => {
154
+ const m = _domain as Record<string, unknown>
155
+ if (_isEntityMap(m[${JSON.stringify(domain)}])) return m[${JSON.stringify(domain)}]
156
+ if (_isEntityMap(m['default'])) return m['default']
157
+ for (const k of Object.keys(m)) if (_isEntityMap(m[k])) return m[k]
158
+ return null
159
+ })()
160
+
161
+ export function createConnector(
162
+ getAccessToken: () => Promise<string | null>,
163
+ config: Record<string, unknown>
164
+ ): unknown {
165
+ const vendor = _vendor as Record<string, unknown>
166
+ if (_domainMap) {
167
+ for (const k of Object.keys(vendor)) {
168
+ const v = vendor[k]
169
+ if (_isEngineClass(v)) {
170
+ return new (v as new (t: unknown, m: unknown) => unknown)(getAccessToken, _domainMap)
171
+ }
172
+ }
173
+ }
174
+ for (const k of Object.keys(vendor)) {
175
+ const v = vendor[k]
176
+ if (typeof v === 'function' && !_isEngineClass(v) && k.startsWith('create')) {
177
+ return (v as (t: unknown, c: unknown) => unknown)(getAccessToken, config)
178
+ }
179
+ }
180
+ throw new Error(
181
+ ${JSON.stringify(`provider module "${domain}" — vendor index exposes no engine class or create* factory`)}
182
+ )
183
+ }
184
+ export default createConnector
185
+ `;
186
+ }
187
+ //# sourceMappingURL=wrappers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wrappers.js","sourceRoot":"","sources":["../src/wrappers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,YAAY,EAAiB,MAAM,qBAAqB,CAAA;AAYjE;;;;;;;;GAQG;AACH,MAAM,cAAc,GAAG,kBAAkB,CAAA;AACzC,MAAM,cAAc,GAAG,mBAAmB,CAAA;AAE1C,2EAA2E;AAC3E,MAAM,UAAU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AU,KAAK,CAAC,IAAI,CAAA;AAClE,CAAC;AAED,0CAA0C;AAE1C,MAAM,qBAAqB,GAAG;;;;;CAK7B,CAAA;AAED;;;;GAIG;AACH,SAAS,oBAAoB,CAAC,IAAY;IACxC,OAAO;wBACe,IAAI,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC;EACjD,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;MAuBjB,IAAI,CAAC,SAAS,CAAC,qBAAqB,IAAI,sEAAsE,CAAC;;;;CAIpH,CAAA;AACD,CAAC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAAC,MAAc;IACzC,OAAO;;2BAEkB,IAAI,CAAC,SAAS,CAAC,KAAK,MAAM,EAAE,CAAC;EACtD,qBAAqB;;;;;;;;;uBASA,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,gBAAgB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;MA0B7E,IAAI,CAAC,SAAS,CAAC,oBAAoB,MAAM,6DAA6D,CAAC;;;;CAI5G,CAAA;AACD,CAAC","sourcesContent":["/**\n * Entry wrappers — the thin module the compiler actually bundles.\n *\n * Which template applies is decided by the kind's `entry` metadata in\n * `@pwfabric/contracts` (`atomKindMeta(kind).entry`), not by\n * ad-hoc \"block vs capability vs connector\" branches:\n *\n * - block (identity) → re-export the component and the definition under\n * the stable names `Component` + `definition`, so the\n * runtime's block module loader reads two fixed keys\n * whatever the author named them.\n * - capability (identity) → opaque `export *` (the handler contract is not\n * normalised).\n * - connector (sibling) → loader-contract adapter: `createConnector` that\n * delegates to an explicit export, wraps an engine\n * class (`prototype.query`), or calls/constructs the\n * default export of the sibling `./<Name>`.\n * - provider (sibling) → per-facet entry over the SHARED vendor motor\n * (`../index`): binds the domain's entity map from\n * `./<domain>` into the vendor engine class, or falls\n * back to a vendor `create*` factory.\n *\n * @module @pwfabric/compiler/wrappers\n */\nimport { atomKindMeta, type AtomKind } from '@pwfabric/contracts'\n\n/**\n * Context passed to the wrapper registry. `identity` kinds supply `sourceBase`\n * (basename of the atom's own source, no extension); `sibling-generated` kinds\n * supply `engineName` (connector `<Name>` / provider `<domain>`).\n */\nexport interface WrapperContext {\n readonly sourceBase?: string\n readonly engineName?: string\n}\n\n/**\n * NAMES ARE UNTRUSTED. `engineName` and `sourceBase` come from pack folder and\n * file names, and they are written into generated SOURCE — a name carrying a\n * quote, a newline or `'; …; //` would be code that no screen ever looked at.\n * Two defences, both always on: the name must match a strict pattern (checked\n * here and, as a diagnostic, by `compileAtom` before it gets this far), and\n * every specifier, property key and message built from a name is emitted\n * through `JSON.stringify`, never spliced between hand-written quotes.\n */\nconst ENGINE_NAME_RE = /^[A-Za-z0-9_-]+$/\nconst SOURCE_BASE_RE = /^[A-Za-z0-9_.-]+$/\n\n/** Connector `<Name>` / provider `<domain>`: letters, digits, `_`, `-`. */\nexport function isValidEngineName(name: string): boolean {\n return ENGINE_NAME_RE.test(name)\n}\n\n/** Entry basename without extension: letters, digits, `_`, `-`, `.` — never `..`. */\nexport function isValidSourceBase(base: string): boolean {\n return SOURCE_BASE_RE.test(base) && !base.includes('..') && base !== '.'\n}\n\n/**\n * The single wrapper registry, keyed off the kind's contract metadata.\n * Throws on a name that fails {@link isValidEngineName} / {@link isValidSourceBase}.\n */\nexport function buildWrapperSource(kind: AtomKind, ctx: WrapperContext): string {\n const meta = atomKindMeta(kind)\n if (meta.entry === 'sibling-generated') {\n const name = ctx.engineName ?? ''\n if (!isValidEngineName(name)) throw new Error(`invalid engine name ${JSON.stringify(name)}`)\n return kind === 'provider' ? providerEntrySource(name) : connectorEntrySource(name)\n }\n // identity\n const sourceBase = ctx.sourceBase ?? ''\n if (!isValidSourceBase(sourceBase)) throw new Error(`invalid entry basename ${JSON.stringify(sourceBase)}`)\n if (kind === 'block') {\n return `import * as _atom from ${JSON.stringify(`./${sourceBase}.js`)}\n\nconst _isDef = (v) =>\n v != null && typeof v === 'object' && 'type' in v && 'schema' in v\n\nconst _resolveDefinition = (m) => {\n for (const k of Object.keys(m)) {\n const v = m[k]\n if (_isDef(v)) return v\n }\n return null\n}\n\nconst _resolveComponent = (m) => {\n if (typeof m.default === 'function') return m.default\n for (const k of Object.keys(m)) {\n const v = m[k]\n if (typeof v === 'function') return v\n }\n return null\n}\n\nexport const definition = _resolveDefinition(_atom)\nexport const Component = _resolveComponent(_atom)\n`\n }\n // capability + any other identity kind\n return `export * from ${JSON.stringify(`./${sourceBase}.js`)}\\n`\n}\n\n// ── sibling-generated engine adapters ──\n\nconst SHARED_ENGINE_HELPERS = `\nconst _isEngineClass = (v: unknown): boolean =>\n typeof v === 'function' &&\n !!(v as { prototype?: { query?: unknown } }).prototype &&\n typeof (v as { prototype: { query?: unknown } }).prototype.query === 'function'\n`\n\n/**\n * Wrapper for kind='connector' — adapts `connectors/<Name>.ts` to the loader\n * contract. Priority: explicit `createConnector` export → engine class\n * (`prototype.query`) → default export (called or constructed).\n */\nfunction connectorEntrySource(name: string): string {\n return `// AUTO-GENERATED (pwfabric-compiler) — loader-contract adapter.\nimport * as _mod from ${JSON.stringify(`./${name}`)}\n${SHARED_ENGINE_HELPERS}\nexport function createConnector(\n getAccessToken: () => Promise<string | null>,\n config: Record<string, unknown>\n): unknown {\n const m = _mod as Record<string, unknown>\n const direct = m['createConnector']\n if (typeof direct === 'function' && !_isEngineClass(direct)) {\n return (direct as (t: unknown, c: unknown) => unknown)(getAccessToken, config)\n }\n for (const k of Object.keys(m)) {\n const v = m[k]\n if (_isEngineClass(v)) {\n return new (v as new (t: unknown, c: unknown) => unknown)(getAccessToken, config)\n }\n }\n const d = m['default']\n if (typeof d === 'function') {\n return _isEngineClass(d)\n ? new (d as new (t: unknown, c: unknown) => unknown)(getAccessToken, config)\n : (d as (t: unknown, c: unknown) => unknown)(getAccessToken, config)\n }\n throw new Error(\n ${JSON.stringify(`connector module \"${name}\" exports no engine (createConnector / class with query() / default)`)}\n )\n}\nexport default createConnector\n`\n}\n\n/**\n * Wrapper for kind='provider' — thin per-facet entry over the SHARED vendor\n * motor. Binds the domain: the entity module's EntityMap + the vendor index's\n * engine class (`new Engine(getAccessToken, domainMap)`). Falls back to a\n * vendor-level `create*` factory (all-domain engine) when no engine class is\n * exported.\n */\nfunction providerEntrySource(domain: string): string {\n return `// AUTO-GENERATED (pwfabric-compiler) — per-facet engine entry.\nimport * as _vendor from '../index'\nimport * as _domain from ${JSON.stringify(`./${domain}`)}\n${SHARED_ENGINE_HELPERS}\nconst _isEntityMap = (v: unknown): boolean => {\n if (!v || typeof v !== 'object' || Array.isArray(v)) return false\n const vals = Object.values(v as Record<string, unknown>)\n return vals.length > 0 && vals.every((x) => !!x && typeof x === 'object')\n}\n\nconst _domainMap = (() => {\n const m = _domain as Record<string, unknown>\n if (_isEntityMap(m[${JSON.stringify(domain)}])) return m[${JSON.stringify(domain)}]\n if (_isEntityMap(m['default'])) return m['default']\n for (const k of Object.keys(m)) if (_isEntityMap(m[k])) return m[k]\n return null\n})()\n\nexport function createConnector(\n getAccessToken: () => Promise<string | null>,\n config: Record<string, unknown>\n): unknown {\n const vendor = _vendor as Record<string, unknown>\n if (_domainMap) {\n for (const k of Object.keys(vendor)) {\n const v = vendor[k]\n if (_isEngineClass(v)) {\n return new (v as new (t: unknown, m: unknown) => unknown)(getAccessToken, _domainMap)\n }\n }\n }\n for (const k of Object.keys(vendor)) {\n const v = vendor[k]\n if (typeof v === 'function' && !_isEngineClass(v) && k.startsWith('create')) {\n return (v as (t: unknown, c: unknown) => unknown)(getAccessToken, config)\n }\n }\n throw new Error(\n ${JSON.stringify(`provider module \"${domain}\" — vendor index exposes no engine class or create* factory`)}\n )\n}\nexport default createConnector\n`\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@pwfabric/compiler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-rc.1",
4
+ "description": "PWFabric atom compiler: block and capability source to one ES module the runtime loads",
5
+ "type": "module",
6
+ "license": "BUSL-1.1",
7
+ "author": "PhiMajor Solutions",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/pwfabric/pwfabric.git",
11
+ "directory": "packages/compiler"
12
+ },
13
+ "homepage": "https://github.com/pwfabric/pwfabric#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/pwfabric/pwfabric/issues"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "LICENSE",
29
+ "README.md"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "dependencies": {
35
+ "esbuild": "0.25.12",
36
+ "@pwfabric/contracts": "1.0.0-rc.1",
37
+ "@pwfabric/core": "1.0.0-rc.1"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.0.0",
41
+ "@vitest/coverage-v8": "^2.1.9",
42
+ "typescript": "^5.4.0",
43
+ "vitest": "^2.0.0"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "rm -rf dist tsconfig.tsbuildinfo && tsc",
50
+ "dev": "tsc --watch",
51
+ "test": "vitest run",
52
+ "test:watch": "vitest",
53
+ "test:coverage": "vitest run --coverage",
54
+ "lint": "eslint src",
55
+ "lint:fix": "eslint src --fix",
56
+ "typecheck": "tsc --noEmit",
57
+ "clean": "rm -rf dist"
58
+ }
6
59
  }