@ankhorage/projects 0.8.0 → 0.9.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/README.md +2 -1
- package/dist/features/projects/composition/composeGeneratedRuntimeMaterialization.js +1 -1
- package/dist/features/projects/composition/createExpoProjectMaterializer.d.ts +4 -6
- package/dist/features/projects/composition/createExpoProjectMaterializer.js +27 -38
- package/dist/features/projects/composition/createNavigatorMaterializationFiles.d.ts +14 -0
- package/dist/features/projects/composition/createNavigatorMaterializationFiles.js +19 -0
- package/dist/features/projects/composition/formatTypeScriptLiteral.js +3 -1
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixHost.d.ts +1 -2
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixHost.js +3 -59
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.d.ts +36 -0
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js +105 -0
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.d.ts +35 -0
- package/dist/features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js +92 -0
- package/dist/features/trusted-zefix-host/composition/zefixOperations.d.ts +20 -0
- package/dist/features/trusted-zefix-host/composition/zefixOperations.js +57 -0
- package/dist/features/worker-materialization/composition/composeWorkerMaterialization.d.ts +13 -0
- package/dist/features/worker-materialization/composition/composeWorkerMaterialization.js +90 -0
- package/dist/features/worker-materialization/composition/createWorkerMaterializationFile.d.ts +13 -0
- package/dist/features/worker-materialization/composition/createWorkerMaterializationFile.js +48 -0
- package/dist/features/worker-materialization/constants/worker.d.ts +6 -0
- package/dist/features/worker-materialization/constants/worker.js +6 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/worker/index.d.ts +3 -0
- package/dist/worker/index.js +3 -0
- package/package.json +12 -8
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
# Ankhorage Projects
|
|
5
5
|
|
|
6
|
-
         
|
|
7
7
|
|
|
8
8
|
Provides standalone project identity, persistence, and repository-oriented project actions.
|
|
9
9
|
|
|
@@ -18,6 +18,7 @@ Open `./paradox/index.html` locally in your browser to browse the complete docum
|
|
|
18
18
|
<a href="https://github.com/artiphishle"><img src="https://avatars.githubusercontent.com/u/137318798?s=64" width="40" height="40" alt="artiphishle" /></a>
|
|
19
19
|
<a href="https://github.com/ankhorage-renovate-sync%5Bbot%5D"><img src="https://avatars.githubusercontent.com/u/323340348?s=64" width="40" height="40" alt="ankhorage-renovate-sync%5Bbot%5D" /></a>
|
|
20
20
|
<a href="https://github.com/faeb187"><img src="https://avatars.githubusercontent.com/u/389333?s=64" width="40" height="40" alt="faeb187" /></a>
|
|
21
|
+
<a href="https://github.com/claude"><img src="https://avatars.githubusercontent.com/u/81847?s=64" width="40" height="40" alt="claude" /></a>
|
|
21
22
|
|
|
22
23
|
## Donation
|
|
23
24
|
|
|
@@ -18,7 +18,7 @@ export function composeGeneratedRuntimeMaterialization(input) {
|
|
|
18
18
|
dependencies: {
|
|
19
19
|
...packageJson.dependencies,
|
|
20
20
|
...input.runtimeDependencies,
|
|
21
|
-
...(input.socialManager ? { '@ankhorage/projects': '^0.
|
|
21
|
+
...(input.socialManager ? { '@ankhorage/projects': '^0.9.0' } : {}),
|
|
22
22
|
},
|
|
23
23
|
devDependencies: {
|
|
24
24
|
...packageJson.devDependencies,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { AppCategory } from '@ankhorage/contracts';
|
|
2
|
-
import type { NavigatorGenerationBindings, NavigatorRuntimePlatform } from '@ankhorage/contracts/navigator';
|
|
3
2
|
import type { Project, ProjectManifestRevision } from '../../../types/projects.js';
|
|
3
|
+
import { type NavigatorMaterializationInput } from './createNavigatorMaterializationFiles.js';
|
|
4
4
|
/*** Inputs fixed by the host before materializing one immutable Projects revision. */
|
|
5
5
|
export interface CreateExpoProjectMaterializerInput {
|
|
6
6
|
readonly targetDirectory: string;
|
|
@@ -8,11 +8,9 @@ export interface CreateExpoProjectMaterializerInput {
|
|
|
8
8
|
category: AppCategory;
|
|
9
9
|
slug: string;
|
|
10
10
|
}>;
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
readonly expoRouterVersion: string;
|
|
15
|
-
}>;
|
|
11
|
+
/** Manifest environment this build targets; Worker hosting is generated only when it runs on Workers. */
|
|
12
|
+
readonly targetEnvironment?: string;
|
|
13
|
+
readonly navigator: NavigatorMaterializationInput;
|
|
16
14
|
}
|
|
17
15
|
/*** The public result of materializing one runnable, self-contained Expo project directory. */
|
|
18
16
|
export interface ExpoProjectMaterializationResult {
|
|
@@ -2,10 +2,10 @@ import { lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile, } fr
|
|
|
2
2
|
import { basename, dirname, relative, resolve } from 'node:path';
|
|
3
3
|
import { resolveExpoRuntimeGeneratedAppScaffold, resolveExpoRuntimeGeneratedAppSources, } from '@ankhorage/expo-runtime/generated-app';
|
|
4
4
|
import { resolveExpoRuntimePlan } from '@ankhorage/expo-runtime/planning';
|
|
5
|
-
import { createNavigatorPlan, generateNavigator } from '@ankhorage/navigator';
|
|
6
5
|
import { materializeTemplateRevision } from '@ankhorage/templates';
|
|
6
|
+
import { applyWorkerMaterialization } from '../../worker-materialization/composition/composeWorkerMaterialization.js';
|
|
7
7
|
import { composeGeneratedRuntimeMaterialization } from './composeGeneratedRuntimeMaterialization.js';
|
|
8
|
-
import {
|
|
8
|
+
import { createNavigatorMaterializationFiles, } from './createNavigatorMaterializationFiles.js';
|
|
9
9
|
import { createSocialManagerServerFiles } from './createSocialManagerServerFiles.js';
|
|
10
10
|
import { formatTypeScriptLiteral } from './formatTypeScriptLiteral.js';
|
|
11
11
|
/*** Create the public, caller-targeted Expo materializer for stored immutable project revisions. */
|
|
@@ -18,7 +18,7 @@ export function createExpoProjectMaterializer(input) {
|
|
|
18
18
|
async function materializeExpoProjectAsync(input, project, revision) {
|
|
19
19
|
assertReleasedOwnerApis();
|
|
20
20
|
const targetDirectory = await assertEmptyTargetDirectoryAsync(input.targetDirectory);
|
|
21
|
-
const generatedFiles = createGeneratedFiles(revision.manifest, input.navigator);
|
|
21
|
+
const generatedFiles = createGeneratedFiles(revision.manifest, project.id, input.navigator, input.targetEnvironment);
|
|
22
22
|
const stagingDirectory = await mkdtemp(`${dirname(targetDirectory)}/.ankhorage-projects-`);
|
|
23
23
|
try {
|
|
24
24
|
const template = await ownerApis.materializeTemplateRevision({
|
|
@@ -37,59 +37,52 @@ async function materializeExpoProjectAsync(input, project, revision) {
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
/*** Produce every Runtime- and Navigator-owned file before Template or target filesystem writes. */
|
|
40
|
-
function createGeneratedFiles(manifest, navigatorInput) {
|
|
41
|
-
const
|
|
40
|
+
function createGeneratedFiles(manifest, projectId, navigatorInput, targetEnvironment) {
|
|
41
|
+
const runtimePlan = ownerApis.resolveExpoRuntimePlan(manifest);
|
|
42
|
+
assertNoErrors(runtimePlan.diagnostics, 'Expo Runtime');
|
|
43
|
+
const runtime = createRuntimeSources(manifest, runtimePlan);
|
|
44
|
+
const scaffold = ownerApis.resolveExpoRuntimeGeneratedAppScaffold(manifest, runtimePlan, targetEnvironment === undefined ? {} : { environment: targetEnvironment });
|
|
42
45
|
const socialManagerFiles = createSocialManagerServerFiles(manifest);
|
|
43
46
|
const packageSource = composeGeneratedRuntimeMaterialization({
|
|
44
47
|
callerBindings: navigatorInput.bindings,
|
|
45
|
-
packageSource:
|
|
46
|
-
runtimeBindings:
|
|
47
|
-
runtimeDependencies:
|
|
48
|
+
packageSource: scaffold.files.find(({ relativePath }) => relativePath === 'package.json')?.source ?? '',
|
|
49
|
+
runtimeBindings: runtime.navigatorBindings,
|
|
50
|
+
runtimeDependencies: runtime.dependencies,
|
|
48
51
|
socialManager: socialManagerFiles.length > 0,
|
|
49
52
|
});
|
|
50
|
-
const
|
|
51
|
-
platform: navigatorInput.platform,
|
|
52
|
-
expoRouterVersion: navigatorInput.expoRouterVersion,
|
|
53
|
-
});
|
|
54
|
-
const navigator = ownerApis.generateNavigator(navigatorPlan, packageSource.navigatorBindings, createRootNavigatorGenerationOptions(manifest));
|
|
55
|
-
assertNoErrors(navigator.diagnostics, 'Navigator');
|
|
53
|
+
const app = applyWorkerMaterialization(manifest, projectId, packageSource.packageSource, targetEnvironment);
|
|
56
54
|
const files = [
|
|
57
|
-
...
|
|
55
|
+
...createScaffoldMaterializationFiles(scaffold.files, app.packageSource),
|
|
56
|
+
...runtime.files.map((file) => ({
|
|
58
57
|
relativePath: file.relativePath,
|
|
59
|
-
source: file.
|
|
58
|
+
source: file.source,
|
|
60
59
|
})),
|
|
61
60
|
{
|
|
62
61
|
relativePath: 'src/ankh.manifest.ts',
|
|
63
62
|
source: `export default ${formatTypeScriptLiteral(manifest)} as const;\n`,
|
|
64
63
|
},
|
|
65
|
-
...
|
|
66
|
-
|
|
67
|
-
source: file.contents,
|
|
68
|
-
})),
|
|
64
|
+
...app.files,
|
|
65
|
+
...createNavigatorMaterializationFiles(manifest, navigatorInput, packageSource.navigatorBindings),
|
|
69
66
|
...socialManagerFiles,
|
|
70
67
|
];
|
|
71
68
|
assertUniqueRelativePaths(files.map(({ relativePath }) => relativePath));
|
|
72
69
|
return files;
|
|
73
70
|
}
|
|
74
|
-
/***
|
|
75
|
-
function
|
|
76
|
-
|
|
77
|
-
|
|
71
|
+
/*** Replace only the scaffold package manifest with the fully composed generated application manifest. */
|
|
72
|
+
function createScaffoldMaterializationFiles(files, packageSource) {
|
|
73
|
+
return files.map((file) => ({
|
|
74
|
+
relativePath: file.relativePath,
|
|
75
|
+
source: file.relativePath === 'package.json' ? packageSource : file.source,
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
/*** Emit and validate the Runtime-owned source plan before it is composed with Navigator or Worker files. */
|
|
79
|
+
function createRuntimeSources(manifest, runtimePlan) {
|
|
78
80
|
const runtime = ownerApis.resolveExpoRuntimeGeneratedAppSources(manifest, runtimePlan, {
|
|
79
81
|
manifestModuleSpecifier: '../ankh.manifest',
|
|
80
82
|
screenModuleSpecifier: '../generated/runtimeManifestScreens',
|
|
81
83
|
});
|
|
82
84
|
assertNoErrors(runtime.diagnostics, 'Expo Runtime');
|
|
83
|
-
|
|
84
|
-
return {
|
|
85
|
-
dependencies: runtime.dependencies,
|
|
86
|
-
files: [
|
|
87
|
-
...scaffold.files,
|
|
88
|
-
...runtime.files.map((file) => ({ relativePath: file.relativePath, source: file.source })),
|
|
89
|
-
],
|
|
90
|
-
navigatorBindings: runtime.navigatorBindings,
|
|
91
|
-
packageSource: scaffold.files.find(({ relativePath }) => relativePath === 'package.json')?.source ?? '',
|
|
92
|
-
};
|
|
85
|
+
return runtime;
|
|
93
86
|
}
|
|
94
87
|
/*** Return the stable public materialization identity and complete sorted generated-file inventory. */
|
|
95
88
|
function createMaterializationResult(project, revision, targetDirectory, templateFiles, generatedFiles) {
|
|
@@ -105,8 +98,6 @@ function createMaterializationResult(project, revision, targetDirectory, templat
|
|
|
105
98
|
/*** Narrow the released owner API boundary so optional peer implementations cannot leak into Projects. */
|
|
106
99
|
const ownerApis = {
|
|
107
100
|
materializeTemplateRevision: materializeTemplateRevision,
|
|
108
|
-
createNavigatorPlan: createNavigatorPlan,
|
|
109
|
-
generateNavigator: generateNavigator,
|
|
110
101
|
resolveExpoRuntimePlan: resolveExpoRuntimePlan,
|
|
111
102
|
resolveExpoRuntimeGeneratedAppSources: resolveExpoRuntimeGeneratedAppSources,
|
|
112
103
|
resolveExpoRuntimeGeneratedAppScaffold: resolveExpoRuntimeGeneratedAppScaffold,
|
|
@@ -114,8 +105,6 @@ const ownerApis = {
|
|
|
114
105
|
/*** Reject unavailable owner emitters rather than reproducing their source in Projects. */
|
|
115
106
|
function assertReleasedOwnerApis() {
|
|
116
107
|
if (typeof ownerApis.materializeTemplateRevision !== 'function' ||
|
|
117
|
-
typeof ownerApis.createNavigatorPlan !== 'function' ||
|
|
118
|
-
typeof ownerApis.generateNavigator !== 'function' ||
|
|
119
108
|
typeof ownerApis.resolveExpoRuntimePlan !== 'function' ||
|
|
120
109
|
typeof ownerApis.resolveExpoRuntimeGeneratedAppSources !== 'function' ||
|
|
121
110
|
typeof ownerApis.resolveExpoRuntimeGeneratedAppScaffold !== 'function') {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AppManifest } from '@ankhorage/contracts';
|
|
2
|
+
import type { NavigatorGenerationBindings, NavigatorRuntimePlatform } from '@ankhorage/contracts/navigator';
|
|
3
|
+
export interface NavigatorMaterializationInput {
|
|
4
|
+
readonly bindings: NavigatorGenerationBindings;
|
|
5
|
+
readonly platform: NavigatorRuntimePlatform;
|
|
6
|
+
readonly expoRouterVersion: string;
|
|
7
|
+
}
|
|
8
|
+
interface MaterializedFile {
|
|
9
|
+
readonly relativePath: string;
|
|
10
|
+
readonly source: string;
|
|
11
|
+
}
|
|
12
|
+
/*** Generate Navigator's route files from the composed Runtime and caller bindings. */
|
|
13
|
+
export declare function createNavigatorMaterializationFiles(manifest: AppManifest, navigatorInput: NavigatorMaterializationInput, bindings: NavigatorGenerationBindings): readonly MaterializedFile[];
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { createNavigatorPlan, generateNavigator } from '@ankhorage/navigator';
|
|
2
|
+
import { createRootNavigatorGenerationOptions } from './createRootNavigatorGenerationOptions.js';
|
|
3
|
+
/*** Generate Navigator's route files from the composed Runtime and caller bindings. */
|
|
4
|
+
export function createNavigatorMaterializationFiles(manifest, navigatorInput, bindings) {
|
|
5
|
+
const navigatorPlan = createNavigatorPlan(manifest.navigator, {
|
|
6
|
+
platform: navigatorInput.platform,
|
|
7
|
+
expoRouterVersion: navigatorInput.expoRouterVersion,
|
|
8
|
+
});
|
|
9
|
+
const navigator = generateNavigator(navigatorPlan, bindings, createRootNavigatorGenerationOptions(manifest));
|
|
10
|
+
assertNoErrors(navigator.diagnostics);
|
|
11
|
+
return navigator.files.map((file) => ({ relativePath: file.path, source: file.contents }));
|
|
12
|
+
}
|
|
13
|
+
/*** Reject Navigator diagnostics that make a generated application invalid before filesystem side effects. */
|
|
14
|
+
function assertNoErrors(diagnostics) {
|
|
15
|
+
const errors = diagnostics.filter(({ severity }) => severity === 'error');
|
|
16
|
+
if (errors.length > 0) {
|
|
17
|
+
throw new Error(`Navigator cannot materialize this revision: ${errors.map(({ message }) => message).join(' ')}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -22,7 +22,9 @@ function formatTypeScriptArray(values, depth) {
|
|
|
22
22
|
}
|
|
23
23
|
/*** Render an object with sorted keys so equal manifests produce equal source. */
|
|
24
24
|
function formatTypeScriptRecord(value, depth) {
|
|
25
|
-
const entries = Object.entries(value)
|
|
25
|
+
const entries = Object.entries(value)
|
|
26
|
+
.filter(([, entryValue]) => entryValue !== undefined)
|
|
27
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
26
28
|
if (entries.length === 0)
|
|
27
29
|
return '{}';
|
|
28
30
|
const indentation = ' '.repeat(depth + 1);
|
|
@@ -3,7 +3,7 @@ import { type FastifyInstance, type RegisterFastifyApiOptions } from '@ankhorage
|
|
|
3
3
|
import type { InternalRestApiDefinition } from '@ankhorage/contracts/data';
|
|
4
4
|
import { type EndpointTestFetch } from '@ankhorage/data-sources';
|
|
5
5
|
import type { SecretStoreAdapter } from '@ankhorage/secrets/port';
|
|
6
|
-
type TrustedZefixOperation
|
|
6
|
+
import { type TrustedZefixOperation } from './zefixOperations.js';
|
|
7
7
|
export type CreateTrustedZefixHostInput = Readonly<{
|
|
8
8
|
appId: string;
|
|
9
9
|
projectId: string;
|
|
@@ -27,4 +27,3 @@ export type TrustedZefixHost = Readonly<{
|
|
|
27
27
|
}>;
|
|
28
28
|
/*** Compose declared Zefix operations into an authenticated, project-scoped trusted host. */
|
|
29
29
|
export declare function createTrustedZefixHost(input: CreateTrustedZefixHostInput): TrustedZefixHost;
|
|
30
|
-
export {};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {} from '@ankhorage/api';
|
|
2
2
|
import { registerAuthorizedFastifyApiAsync, } from '@ankhorage/api-fastify';
|
|
3
|
-
import { createZefixPublicRestApi
|
|
3
|
+
import { createZefixPublicRestApi } from '@ankhorage/data-sources';
|
|
4
4
|
import { createRuntimeApiCapabilityExecutor } from '@ankhorage/runtime/api-capabilities';
|
|
5
|
-
import { isRecord } from '@ankhorage/utility/object';
|
|
6
5
|
import { CAPABILITIES } from '../../../capabilities/index.js';
|
|
6
|
+
import { executeZefixOperationAsync } from './zefixOperations.js';
|
|
7
7
|
/*** Compose declared Zefix operations into an authenticated, project-scoped trusted host. */
|
|
8
8
|
export function createTrustedZefixHost(input) {
|
|
9
9
|
assertHostIdentity(input);
|
|
@@ -36,7 +36,7 @@ export function createTrustedZefixHost(input) {
|
|
|
36
36
|
owner: capability.owner,
|
|
37
37
|
scope: context,
|
|
38
38
|
},
|
|
39
|
-
handler: async (request) => executeZefixOperationAsync(executor, operation, request),
|
|
39
|
+
handler: async (request) => executeZefixOperationAsync(executor, operation, operation === 'company.search' ? request.body : { id: request.params.id }),
|
|
40
40
|
};
|
|
41
41
|
},
|
|
42
42
|
};
|
|
@@ -84,62 +84,6 @@ function createZefixCredentialResolver(input) {
|
|
|
84
84
|
: undefined;
|
|
85
85
|
};
|
|
86
86
|
}
|
|
87
|
-
/*** Execute only an approved Zefix operation and return the curated company projection. */
|
|
88
|
-
async function executeZefixOperationAsync(executor, operation, request) {
|
|
89
|
-
const input = operation === 'company.search' ? request.body : { id: request.params.id };
|
|
90
|
-
const values = isHostBindingRecord(input) ? input : undefined;
|
|
91
|
-
const result = await executor({
|
|
92
|
-
capability: `api.zefix.${operation}`,
|
|
93
|
-
...(values === undefined ? {} : { input: values }),
|
|
94
|
-
});
|
|
95
|
-
if (!result.ok)
|
|
96
|
-
return zefixUnavailableResponse();
|
|
97
|
-
const companies = curateZefixResult(result.data);
|
|
98
|
-
return companies === undefined ? zefixUnavailableResponse() : { body: companies };
|
|
99
|
-
}
|
|
100
|
-
/*** Strip provider wire payloads before any Zefix result crosses the trusted host boundary. */
|
|
101
|
-
function curateZefixResult(value) {
|
|
102
|
-
if (!Array.isArray(value))
|
|
103
|
-
return undefined;
|
|
104
|
-
const mapped = value.map((candidate) => {
|
|
105
|
-
const company = asZefixCompany(candidate);
|
|
106
|
-
return company ? mapZefixCompanyResult(company) : undefined;
|
|
107
|
-
});
|
|
108
|
-
return mapped.every((result) => result !== undefined)
|
|
109
|
-
? mapped.map((result) => result.company)
|
|
110
|
-
: undefined;
|
|
111
|
-
}
|
|
112
|
-
/*** Return the one credential-safe failure representation for Vault or provider failures. */
|
|
113
|
-
function zefixUnavailableResponse() {
|
|
114
|
-
return { status: 502, body: { error: { code: 'zefix_unavailable' } } };
|
|
115
|
-
}
|
|
116
|
-
/*** Narrow unknown endpoint data to the optional-field Zefix short-company DTO. */
|
|
117
|
-
function asZefixCompany(value) {
|
|
118
|
-
return isRecord(value) &&
|
|
119
|
-
optionalString(value.name) &&
|
|
120
|
-
optionalString(value.uid) &&
|
|
121
|
-
optionalString(value.chid) &&
|
|
122
|
-
optionalString(value.legalSeat)
|
|
123
|
-
? value
|
|
124
|
-
: undefined;
|
|
125
|
-
}
|
|
126
|
-
/*** Accept missing or string wire fields while rejecting non-serializable provider data. */
|
|
127
|
-
function optionalString(value) {
|
|
128
|
-
return value === undefined || typeof value === 'string';
|
|
129
|
-
}
|
|
130
|
-
/*** Admit only serializable operation input before passing it to Runtime's binding executor. */
|
|
131
|
-
function isHostBindingRecord(value) {
|
|
132
|
-
return isRecord(value) && Object.values(value).every(isHostBindingValue);
|
|
133
|
-
}
|
|
134
|
-
/*** Recursively reject host objects and functions from untrusted request input. */
|
|
135
|
-
function isHostBindingValue(value) {
|
|
136
|
-
return (value === null ||
|
|
137
|
-
typeof value === 'string' ||
|
|
138
|
-
typeof value === 'number' ||
|
|
139
|
-
typeof value === 'boolean' ||
|
|
140
|
-
(Array.isArray(value) && value.every(isHostBindingValue)) ||
|
|
141
|
-
(isRecord(value) && Object.values(value).every(isHostBindingValue)));
|
|
142
|
-
}
|
|
143
87
|
/*** Resolve the one Projects-owned capability permitted for each declared Zefix operation. */
|
|
144
88
|
function resolveCapability(operation) {
|
|
145
89
|
const id = operation === 'company.search'
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { PersistentExternalRequestBudgetPort } from '@ankhorage/api';
|
|
2
|
+
import type { TrustedZefixOperation } from './zefixOperations.js';
|
|
3
|
+
/*** Worker bindings; every value is resolved server-side and never reaches the client bundle. */
|
|
4
|
+
export type TrustedZefixWorkerEnvironment = Readonly<Record<string, string | undefined>>;
|
|
5
|
+
/*** Provider-neutral caller verification port, structurally compatible with `@ankhorage/auth`. */
|
|
6
|
+
export interface TrustedZefixWorkerCallerAuthentication {
|
|
7
|
+
authenticateCaller(input: Readonly<{
|
|
8
|
+
credential?: string;
|
|
9
|
+
}>): Promise<Readonly<{
|
|
10
|
+
status: string;
|
|
11
|
+
caller?: Readonly<{
|
|
12
|
+
id: string;
|
|
13
|
+
}>;
|
|
14
|
+
}>>;
|
|
15
|
+
}
|
|
16
|
+
/*** Durable request budget with its explicit schema and connection lifecycle. */
|
|
17
|
+
export interface TrustedZefixWorkerRequestBudget extends PersistentExternalRequestBudgetPort {
|
|
18
|
+
ensureSchemaAsync(): Promise<void>;
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export type CreateTrustedZefixWorkerEntryInput = Readonly<{
|
|
22
|
+
appId: string;
|
|
23
|
+
projectId: string;
|
|
24
|
+
environment: string;
|
|
25
|
+
operations: Readonly<Record<string, TrustedZefixOperation>>;
|
|
26
|
+
/** Build the caller verifier from the Worker bindings, for example with Neon Auth. */
|
|
27
|
+
createCallerAuthentication: (env: TrustedZefixWorkerEnvironment) => TrustedZefixWorkerCallerAuthentication;
|
|
28
|
+
/** Build the durable budget from the Worker bindings, for example on Neon PostgreSQL. */
|
|
29
|
+
createRequestBudget: (env: TrustedZefixWorkerEnvironment) => TrustedZefixWorkerRequestBudget;
|
|
30
|
+
}>;
|
|
31
|
+
/*** A Cloudflare Worker module whose fetch handler resolves every binding server-side. */
|
|
32
|
+
export interface TrustedZefixWorkerEntry {
|
|
33
|
+
fetch(request: Request, env: TrustedZefixWorkerEnvironment): Promise<Response>;
|
|
34
|
+
}
|
|
35
|
+
/*** Compose the deployable Worker entry from injected adapters and server-side bindings. */
|
|
36
|
+
export declare function createTrustedZefixWorkerEntry(input: CreateTrustedZefixWorkerEntryInput): TrustedZefixWorkerEntry;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createTrustedZefixWorkerHandler, } from './createTrustedZefixWorkerHandler.js';
|
|
2
|
+
/** Acquisition authorizes exactly two configured subjects; any other configuration denies access. */
|
|
3
|
+
const REQUIRED_SUBJECT_COUNT = 2;
|
|
4
|
+
/*** Compose the deployable Worker entry from injected adapters and server-side bindings. */
|
|
5
|
+
export function createTrustedZefixWorkerEntry(input) {
|
|
6
|
+
// The budget table is created at most once per isolate; a failure is retried, never skipped.
|
|
7
|
+
const schema = { ready: false };
|
|
8
|
+
return {
|
|
9
|
+
fetch: async (request, env) => {
|
|
10
|
+
const budget = createBudget(input, env);
|
|
11
|
+
if (budget === undefined)
|
|
12
|
+
return unavailable();
|
|
13
|
+
try {
|
|
14
|
+
if (!schema.ready) {
|
|
15
|
+
await budget.ensureSchemaAsync();
|
|
16
|
+
schema.ready = true;
|
|
17
|
+
}
|
|
18
|
+
return await createRequestHandler(input, env, budget)(request);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return unavailable();
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
await budget.close().catch(() => undefined);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/*** Create the budget, treating any construction failure as an unavailable host. */
|
|
30
|
+
function createBudget(input, env) {
|
|
31
|
+
try {
|
|
32
|
+
return input.createRequestBudget(env);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/*** Bind the shared trusted handler to this request's verified, allow-listed caller and secrets. */
|
|
39
|
+
function createRequestHandler(input, env, requestBudget) {
|
|
40
|
+
const authentication = input.createCallerAuthentication(env);
|
|
41
|
+
const allowedSubjects = parseAllowedSubjects(env.ANKH_AUTH_ALLOWED_SUBJECTS);
|
|
42
|
+
return createTrustedZefixWorkerHandler({
|
|
43
|
+
appId: input.appId,
|
|
44
|
+
projectId: input.projectId,
|
|
45
|
+
environment: input.environment,
|
|
46
|
+
operations: input.operations,
|
|
47
|
+
requestBudget,
|
|
48
|
+
authenticateCallerAsync: async (request) => {
|
|
49
|
+
const result = await authentication.authenticateCaller(withCredential(readBearerCredential(request)));
|
|
50
|
+
return result.status === 'authenticated' ? result.caller : undefined;
|
|
51
|
+
},
|
|
52
|
+
// Deny every caller unless the server-side allow-list names their verified subject.
|
|
53
|
+
authorizeCallerAsync: ({ caller }) => Promise.resolve(isCallerWithId(caller) && allowedSubjects.has(caller.id)),
|
|
54
|
+
resolveCredentialsAsync: () => Promise.resolve(parseCredentials(env.ZEFIX_CREDENTIALS)),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/*** Read the bearer credential from the Authorization header only. */
|
|
58
|
+
function readBearerCredential(request) {
|
|
59
|
+
const match = /^Bearer\s+(\S+)$/iu.exec(request.headers.get('authorization')?.trim() ?? '');
|
|
60
|
+
return match?.[1];
|
|
61
|
+
}
|
|
62
|
+
/*** Keep the optional credential property absent rather than undefined. */
|
|
63
|
+
function withCredential(credential) {
|
|
64
|
+
return credential === undefined ? {} : { credential };
|
|
65
|
+
}
|
|
66
|
+
/*** Parse the server-side subject allow-list: exactly two distinct subject IDs, otherwise nobody is allowed. */
|
|
67
|
+
function parseAllowedSubjects(value) {
|
|
68
|
+
const subjects = (value ?? '')
|
|
69
|
+
.split(/[\s,]+/u)
|
|
70
|
+
.map((subject) => subject.trim())
|
|
71
|
+
.filter((subject) => subject.length > 0);
|
|
72
|
+
const distinct = new Set(subjects);
|
|
73
|
+
return subjects.length === REQUIRED_SUBJECT_COUNT && distinct.size === REQUIRED_SUBJECT_COUNT
|
|
74
|
+
? distinct
|
|
75
|
+
: new Set();
|
|
76
|
+
}
|
|
77
|
+
/*** Parse the server-side Zefix Basic credentials; malformed values count as unavailable. */
|
|
78
|
+
function parseCredentials(value) {
|
|
79
|
+
try {
|
|
80
|
+
const parsed = JSON.parse(value ?? '');
|
|
81
|
+
return isCredentialRecord(parsed) ? parsed : undefined;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/*** Narrow parsed JSON to non-empty Basic credentials. */
|
|
88
|
+
function isCredentialRecord(value) {
|
|
89
|
+
return (typeof value === 'object' &&
|
|
90
|
+
value !== null &&
|
|
91
|
+
'username' in value &&
|
|
92
|
+
'password' in value &&
|
|
93
|
+
typeof value.username === 'string' &&
|
|
94
|
+
typeof value.password === 'string' &&
|
|
95
|
+
value.username.length > 0 &&
|
|
96
|
+
value.password.length > 0);
|
|
97
|
+
}
|
|
98
|
+
/*** Narrow the verified caller to an identity-bearing record. */
|
|
99
|
+
function isCallerWithId(caller) {
|
|
100
|
+
return (typeof caller === 'object' && caller !== null && 'id' in caller && typeof caller.id === 'string');
|
|
101
|
+
}
|
|
102
|
+
/*** Return the one caller-safe response for any host failure. */
|
|
103
|
+
function unavailable() {
|
|
104
|
+
return Response.json({ error: { code: 'external_request_unavailable' } }, { status: 503, headers: { 'cache-control': 'no-store' } });
|
|
105
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type PersistentExternalRequestBudgetPort } from '@ankhorage/api';
|
|
2
|
+
import { type EndpointTestFetch, type EndpointTestFetchInit } from '@ankhorage/data-sources';
|
|
3
|
+
import { type TrustedZefixOperation } from './zefixOperations.js';
|
|
4
|
+
/*** Basic credentials resolved by the trusted host, for example from a Worker secret binding. */
|
|
5
|
+
export type TrustedZefixWorkerCredentials = Readonly<{
|
|
6
|
+
username: string;
|
|
7
|
+
password: string;
|
|
8
|
+
}>;
|
|
9
|
+
/*** Outbound transport that receives the reservation's abort signal and must not follow redirects. */
|
|
10
|
+
export type TrustedZefixWorkerFetch = (url: string, init: EndpointTestFetchInit & Readonly<{
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
redirect: 'error';
|
|
13
|
+
}>) => ReturnType<EndpointTestFetch>;
|
|
14
|
+
export type CreateTrustedZefixWorkerHandlerInput = Readonly<{
|
|
15
|
+
appId: string;
|
|
16
|
+
projectId: string;
|
|
17
|
+
environment: string;
|
|
18
|
+
/** The application allowlist: broker operation ids permitted to reach each Zefix operation. */
|
|
19
|
+
operations: Readonly<Record<string, TrustedZefixOperation>>;
|
|
20
|
+
/** Verify the caller session, for example with Neon Auth; never trust caller-supplied identity. */
|
|
21
|
+
authenticateCallerAsync: (request: Request) => Promise<unknown>;
|
|
22
|
+
authorizeCallerAsync: (input: Readonly<{
|
|
23
|
+
caller: unknown;
|
|
24
|
+
appId: string;
|
|
25
|
+
projectId: string;
|
|
26
|
+
environment: string;
|
|
27
|
+
operationId: string;
|
|
28
|
+
}>) => Promise<boolean>;
|
|
29
|
+
/** Durable atomic admission, for example the PostgreSQL request budget. */
|
|
30
|
+
requestBudget: PersistentExternalRequestBudgetPort;
|
|
31
|
+
resolveCredentialsAsync: () => Promise<TrustedZefixWorkerCredentials | undefined>;
|
|
32
|
+
fetch?: TrustedZefixWorkerFetch;
|
|
33
|
+
}>;
|
|
34
|
+
/*** Compose the Fetch-standard Zefix Worker handler from injected, provider-neutral host ports. */
|
|
35
|
+
export declare function createTrustedZefixWorkerHandler(input: CreateTrustedZefixWorkerHandlerInput): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { createWorkerTrustedApiHandler, } from '@ankhorage/api';
|
|
2
|
+
import { createZefixPublicRestApi, } from '@ankhorage/data-sources';
|
|
3
|
+
import { createRuntimeApiCapabilityExecutor } from '@ankhorage/runtime/api-capabilities';
|
|
4
|
+
import { executeZefixOperationAsync, isHostBindingRecord, } from './zefixOperations.js';
|
|
5
|
+
/*** Compose the Fetch-standard Zefix Worker handler from injected, provider-neutral host ports. */
|
|
6
|
+
export function createTrustedZefixWorkerHandler(input) {
|
|
7
|
+
if (!input.appId.trim() || !input.projectId.trim() || !input.environment.trim())
|
|
8
|
+
throw new Error('Trusted Zefix host requires immutable app, project, and environment identities.');
|
|
9
|
+
const operations = new Map(Object.entries(input.operations));
|
|
10
|
+
const fetchImpl = input.fetch ?? defaultFetchAsync;
|
|
11
|
+
return createWorkerTrustedApiHandler({
|
|
12
|
+
scope: { appId: input.appId, projectId: input.projectId, environment: input.environment },
|
|
13
|
+
authenticateCallerAsync: input.authenticateCallerAsync,
|
|
14
|
+
broker: {
|
|
15
|
+
requestBudget: input.requestBudget,
|
|
16
|
+
authorizeAsync: async ({ context, request }) => input
|
|
17
|
+
.authorizeCallerAsync({
|
|
18
|
+
caller: context.caller,
|
|
19
|
+
...context.scope,
|
|
20
|
+
operationId: request.operationId,
|
|
21
|
+
})
|
|
22
|
+
.catch(() => false),
|
|
23
|
+
resolveOperationAsync: ({ request }) => resolveOperation(operations, request),
|
|
24
|
+
validateInputAsync: ({ input: value }) => {
|
|
25
|
+
if (!isHostBindingRecord(value))
|
|
26
|
+
throw new TypeError('Invalid operation input.');
|
|
27
|
+
return value;
|
|
28
|
+
},
|
|
29
|
+
resolveCredentialsAsync: async () => {
|
|
30
|
+
const credentials = await input.resolveCredentialsAsync();
|
|
31
|
+
return credentials === undefined ? undefined : { values: { ...credentials } };
|
|
32
|
+
},
|
|
33
|
+
executeOperationAsync: (execution) => executeBrokerOperationAsync(fetchImpl, execution),
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/*** Admit only allowlisted operation ids bound to their one canonical Zefix endpoint. */
|
|
38
|
+
function resolveOperation(operations, request) {
|
|
39
|
+
const zefix = operations.get(request.operationId);
|
|
40
|
+
return zefix !== undefined &&
|
|
41
|
+
request.apiId === 'zefix' &&
|
|
42
|
+
request.endpointId === canonicalEndpointId(zefix)
|
|
43
|
+
? {
|
|
44
|
+
apiId: 'zefix',
|
|
45
|
+
endpointId: request.endpointId,
|
|
46
|
+
operationId: request.operationId,
|
|
47
|
+
credentialsRequired: true,
|
|
48
|
+
zefix,
|
|
49
|
+
}
|
|
50
|
+
: undefined;
|
|
51
|
+
}
|
|
52
|
+
/*** Bind each Zefix operation to its one canonical endpoint id. */
|
|
53
|
+
function canonicalEndpointId(operation) {
|
|
54
|
+
return operation === 'company.search' ? 'company-search' : 'company-uid';
|
|
55
|
+
}
|
|
56
|
+
/*** Execute one admitted operation with abort-aware transport and server-side Basic credentials. */
|
|
57
|
+
async function executeBrokerOperationAsync(fetchImpl, execution) {
|
|
58
|
+
const { credentials, signal } = execution;
|
|
59
|
+
const executor = createRuntimeApiCapabilityExecutor({
|
|
60
|
+
apis: { zefix: createZefixPublicRestApi() },
|
|
61
|
+
credentialResolver: () => Promise.resolve(credentials === undefined
|
|
62
|
+
? undefined
|
|
63
|
+
: {
|
|
64
|
+
headers: {
|
|
65
|
+
authorization: `Basic ${btoa(`${credentials.values.username}:${credentials.values.password}`)}`,
|
|
66
|
+
},
|
|
67
|
+
}),
|
|
68
|
+
// Every admitted execution is abortable and issues at most the one Zefix request.
|
|
69
|
+
fetch: createSingleRequestFetch(fetchImpl, signal),
|
|
70
|
+
});
|
|
71
|
+
const result = await executeZefixOperationAsync(executor, execution.operation.zefix, execution.input);
|
|
72
|
+
return { status: 'status' in result ? result.status : 200, publicBody: result.body };
|
|
73
|
+
}
|
|
74
|
+
/*** Allow exactly one upstream request per reservation: no second call, redirect or retry. */
|
|
75
|
+
function createSingleRequestFetch(fetchImpl, signal) {
|
|
76
|
+
const state = { used: false };
|
|
77
|
+
return (url, init) => {
|
|
78
|
+
if (state.used)
|
|
79
|
+
return Promise.reject(new Error('Only one upstream request is permitted.'));
|
|
80
|
+
state.used = true;
|
|
81
|
+
return fetchImpl(url, {
|
|
82
|
+
...init,
|
|
83
|
+
redirect: 'error',
|
|
84
|
+
...(signal === undefined ? {} : { signal }),
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/*** Use the platform fetch and expose only the response surface the runtime executor reads. */
|
|
89
|
+
async function defaultFetchAsync(url, init) {
|
|
90
|
+
const response = await fetch(url, init);
|
|
91
|
+
return { status: response.status, text: () => response.text() };
|
|
92
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { createRuntimeApiCapabilityExecutor } from '@ankhorage/runtime/api-capabilities';
|
|
2
|
+
export type TrustedZefixOperation = 'company.search' | 'company.get-by-uid';
|
|
3
|
+
/*** Execute only an approved Zefix operation and return the curated company projection. */
|
|
4
|
+
export declare function executeZefixOperationAsync(executor: ReturnType<typeof createRuntimeApiCapabilityExecutor>, operation: TrustedZefixOperation, input: unknown): Promise<{
|
|
5
|
+
status: number;
|
|
6
|
+
body: {
|
|
7
|
+
error: {
|
|
8
|
+
code: string;
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
} | {
|
|
12
|
+
body: import("@ankhorage/data-sources").ZefixCompanyResultCompany[];
|
|
13
|
+
}>;
|
|
14
|
+
type HostBindingValue = string | number | boolean | null | readonly HostBindingValue[] | HostBindingRecord;
|
|
15
|
+
interface HostBindingRecord {
|
|
16
|
+
readonly [key: string]: HostBindingValue;
|
|
17
|
+
}
|
|
18
|
+
/*** Admit only serializable operation input before passing it to Runtime's binding executor. */
|
|
19
|
+
export declare function isHostBindingRecord(value: unknown): value is HostBindingRecord;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { mapZefixCompanyResult } from '@ankhorage/data-sources';
|
|
2
|
+
import { isRecord } from '@ankhorage/utility/object';
|
|
3
|
+
/*** Execute only an approved Zefix operation and return the curated company projection. */
|
|
4
|
+
export async function executeZefixOperationAsync(executor, operation, input) {
|
|
5
|
+
const values = isHostBindingRecord(input) ? input : undefined;
|
|
6
|
+
const result = await executor({
|
|
7
|
+
capability: `api.zefix.${operation}`,
|
|
8
|
+
...(values === undefined ? {} : { input: values }),
|
|
9
|
+
});
|
|
10
|
+
if (!result.ok)
|
|
11
|
+
return zefixUnavailableResponse();
|
|
12
|
+
const companies = curateZefixResult(result.data);
|
|
13
|
+
return companies === undefined ? zefixUnavailableResponse() : { body: companies };
|
|
14
|
+
}
|
|
15
|
+
/*** Strip provider wire payloads before any Zefix result crosses the trusted host boundary. */
|
|
16
|
+
function curateZefixResult(value) {
|
|
17
|
+
if (!Array.isArray(value))
|
|
18
|
+
return undefined;
|
|
19
|
+
const mapped = value.map((candidate) => {
|
|
20
|
+
const company = asZefixCompany(candidate);
|
|
21
|
+
return company ? mapZefixCompanyResult(company) : undefined;
|
|
22
|
+
});
|
|
23
|
+
return mapped.every((result) => result !== undefined)
|
|
24
|
+
? mapped.map((result) => result.company)
|
|
25
|
+
: undefined;
|
|
26
|
+
}
|
|
27
|
+
/*** Return the one credential-safe failure representation for Vault or provider failures. */
|
|
28
|
+
function zefixUnavailableResponse() {
|
|
29
|
+
return { status: 502, body: { error: { code: 'zefix_unavailable' } } };
|
|
30
|
+
}
|
|
31
|
+
/*** Narrow unknown endpoint data to the optional-field Zefix short-company DTO. */
|
|
32
|
+
function asZefixCompany(value) {
|
|
33
|
+
return isRecord(value) &&
|
|
34
|
+
optionalString(value.name) &&
|
|
35
|
+
optionalString(value.uid) &&
|
|
36
|
+
optionalString(value.chid) &&
|
|
37
|
+
optionalString(value.legalSeat)
|
|
38
|
+
? value
|
|
39
|
+
: undefined;
|
|
40
|
+
}
|
|
41
|
+
/*** Accept missing or string wire fields while rejecting non-serializable provider data. */
|
|
42
|
+
function optionalString(value) {
|
|
43
|
+
return value === undefined || typeof value === 'string';
|
|
44
|
+
}
|
|
45
|
+
/*** Admit only serializable operation input before passing it to Runtime's binding executor. */
|
|
46
|
+
export function isHostBindingRecord(value) {
|
|
47
|
+
return isRecord(value) && Object.values(value).every(isHostBindingValue);
|
|
48
|
+
}
|
|
49
|
+
/*** Recursively reject host objects and functions from untrusted request input. */
|
|
50
|
+
function isHostBindingValue(value) {
|
|
51
|
+
return (value === null ||
|
|
52
|
+
typeof value === 'string' ||
|
|
53
|
+
typeof value === 'number' ||
|
|
54
|
+
typeof value === 'boolean' ||
|
|
55
|
+
(Array.isArray(value) && value.every(isHostBindingValue)) ||
|
|
56
|
+
(isRecord(value) && Object.values(value).every(isHostBindingValue)));
|
|
57
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type AppManifest } from '@ankhorage/contracts';
|
|
2
|
+
/*** One generated file emitted by the Worker generator. */
|
|
3
|
+
interface WorkerMaterializationFile {
|
|
4
|
+
readonly relativePath: string;
|
|
5
|
+
readonly source: string;
|
|
6
|
+
}
|
|
7
|
+
/*** Add the Worker entry and build scripts to a generated package when the target environment runs on Workers. */
|
|
8
|
+
export declare function applyWorkerMaterialization(manifest: AppManifest, projectId: string, packageSource: string, targetEnvironment: string | undefined): Readonly<{
|
|
9
|
+
packageSource: string;
|
|
10
|
+
files: readonly WorkerMaterializationFile[];
|
|
11
|
+
}>;
|
|
12
|
+
export {};
|
|
13
|
+
/*** Render the thin Worker module: bindings are resolved server-side by the shared host. */
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { APP_ENVIRONMENT_IDS } from '@ankhorage/contracts';
|
|
2
|
+
import { WORKER_BUILT_ENTRY, WORKER_ENTRY_SOURCE_PATH, WORKER_WEB_DIRECTORY, } from '../constants/worker.js';
|
|
3
|
+
import { createWorkerMaterializationFile } from './createWorkerMaterializationFile.js';
|
|
4
|
+
const WORKER_DEPENDENCIES = {
|
|
5
|
+
'@ankhorage/auth': '^0.3.0',
|
|
6
|
+
'@ankhorage/auth-neon': '^0.2.0',
|
|
7
|
+
'@ankhorage/db-postgres': '^0.2.0',
|
|
8
|
+
'@ankhorage/projects': '^0.9.0',
|
|
9
|
+
};
|
|
10
|
+
const WORKER_SCRIPTS = {
|
|
11
|
+
'build:web': `expo export --platform web --output-dir ${WORKER_WEB_DIRECTORY}`,
|
|
12
|
+
'build:worker': `bun build ${WORKER_ENTRY_SOURCE_PATH} --outfile ${WORKER_BUILT_ENTRY} --target browser --format esm`,
|
|
13
|
+
build: 'bun run build:web && bun run build:worker',
|
|
14
|
+
};
|
|
15
|
+
const ZEFIX_OPERATIONS = ['company.search', 'company.get-by-uid'];
|
|
16
|
+
/*** Add the Worker entry and build scripts to a generated package when the target environment runs on Workers. */
|
|
17
|
+
export function applyWorkerMaterialization(manifest, projectId, packageSource, targetEnvironment) {
|
|
18
|
+
const worker = composeWorkerMaterialization(manifest, projectId, targetEnvironment);
|
|
19
|
+
return worker === undefined
|
|
20
|
+
? { packageSource, files: [] }
|
|
21
|
+
: { packageSource: composeWorkerPackageSource(packageSource, worker), files: worker.files };
|
|
22
|
+
}
|
|
23
|
+
/*** Generate the Worker entry and build scripts when the target environment deploys to Cloudflare Workers. */
|
|
24
|
+
function composeWorkerMaterialization(manifest, projectId, targetEnvironment) {
|
|
25
|
+
if (targetEnvironment === undefined)
|
|
26
|
+
return undefined;
|
|
27
|
+
const target = resolveTargetEnvironment(manifest, targetEnvironment);
|
|
28
|
+
if (target.deployment.runtime.provider !== 'workers')
|
|
29
|
+
return undefined;
|
|
30
|
+
const scripts = createWorkerScripts(target.auth?.provider);
|
|
31
|
+
// The trusted Zefix handler is composed only when the manifest declares the corresponding API.
|
|
32
|
+
const operations = resolveZefixOperations(manifest);
|
|
33
|
+
return operations.length === 0
|
|
34
|
+
? {
|
|
35
|
+
files: [createWorkerMaterializationFile()],
|
|
36
|
+
dependencies: {},
|
|
37
|
+
scripts,
|
|
38
|
+
}
|
|
39
|
+
: {
|
|
40
|
+
files: [
|
|
41
|
+
createWorkerMaterializationFile({
|
|
42
|
+
appId: manifest.metadata.slug,
|
|
43
|
+
projectId,
|
|
44
|
+
environment: targetEnvironment,
|
|
45
|
+
operations,
|
|
46
|
+
}),
|
|
47
|
+
],
|
|
48
|
+
dependencies: WORKER_DEPENDENCIES,
|
|
49
|
+
scripts,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** Resolve the declared target through the shared application-environment contract. */
|
|
53
|
+
function resolveTargetEnvironment(manifest, targetEnvironment) {
|
|
54
|
+
if (!isAppEnvironmentId(targetEnvironment)) {
|
|
55
|
+
throw new Error(`Target environment "${targetEnvironment}" is not declared in the manifest.`);
|
|
56
|
+
}
|
|
57
|
+
const target = Object.entries(manifest.infra.environments).find(([environment]) => environment === targetEnvironment)?.[1];
|
|
58
|
+
if (target === undefined) {
|
|
59
|
+
throw new Error(`Target environment "${targetEnvironment}" is not declared in the manifest.`);
|
|
60
|
+
}
|
|
61
|
+
return target;
|
|
62
|
+
}
|
|
63
|
+
/** Recognize only application environments declared by the portable contracts package. */
|
|
64
|
+
function isAppEnvironmentId(value) {
|
|
65
|
+
return APP_ENVIRONMENT_IDS.some((environment) => environment === value);
|
|
66
|
+
}
|
|
67
|
+
/*** Map the selected Neon Auth public output into Expo's public build environment only for Neon Auth builds. */
|
|
68
|
+
function createWorkerScripts(authProvider) {
|
|
69
|
+
return authProvider === 'neon'
|
|
70
|
+
? {
|
|
71
|
+
...WORKER_SCRIPTS,
|
|
72
|
+
'build:web': `EXPO_PUBLIC_NEON_AUTH_URL="$NEON_AUTH_BASE_URL" ${WORKER_SCRIPTS['build:web']}`,
|
|
73
|
+
}
|
|
74
|
+
: WORKER_SCRIPTS;
|
|
75
|
+
}
|
|
76
|
+
/*** Add the Worker dependencies and build scripts to the generated application's package.json. */
|
|
77
|
+
function composeWorkerPackageSource(packageSource, worker) {
|
|
78
|
+
const packageJson = JSON.parse(packageSource);
|
|
79
|
+
return `${JSON.stringify({
|
|
80
|
+
...packageJson,
|
|
81
|
+
dependencies: { ...packageJson.dependencies, ...worker.dependencies },
|
|
82
|
+
scripts: { ...packageJson.scripts, ...worker.scripts },
|
|
83
|
+
}, null, 2)}\n`;
|
|
84
|
+
}
|
|
85
|
+
/*** Collect the declared Zefix operations the trusted host can execute. */
|
|
86
|
+
function resolveZefixOperations(manifest) {
|
|
87
|
+
const declared = new Set(Object.values(manifest.infra.apis?.zefix?.endpoints ?? {}).flatMap((endpoint) => Object.values(endpoint.operations).map((operation) => operation.id)));
|
|
88
|
+
return ZEFIX_OPERATIONS.filter((operation) => declared.has(operation));
|
|
89
|
+
}
|
|
90
|
+
/*** Render the thin Worker module: bindings are resolved server-side by the shared host. */
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
interface WorkerMaterializationFile {
|
|
2
|
+
readonly relativePath: string;
|
|
3
|
+
readonly source: string;
|
|
4
|
+
}
|
|
5
|
+
interface WorkerEntryInput {
|
|
6
|
+
readonly appId: string;
|
|
7
|
+
readonly projectId: string;
|
|
8
|
+
readonly environment: string;
|
|
9
|
+
readonly operations: readonly string[];
|
|
10
|
+
}
|
|
11
|
+
/*** Render the generated Worker entry for either trusted API operations or a static-only application. */
|
|
12
|
+
export declare function createWorkerMaterializationFile(input?: WorkerEntryInput): WorkerMaterializationFile;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { WORKER_ENTRY_SOURCE_PATH, WORKER_WEB_DIRECTORY } from '../constants/worker.js';
|
|
2
|
+
/** Maximum requests per budget key admitted by the generated Worker. */
|
|
3
|
+
const WORKER_REQUEST_LIMIT = 10;
|
|
4
|
+
/*** Render the generated Worker entry for either trusted API operations or a static-only application. */
|
|
5
|
+
export function createWorkerMaterializationFile(input) {
|
|
6
|
+
return {
|
|
7
|
+
relativePath: WORKER_ENTRY_SOURCE_PATH,
|
|
8
|
+
source: input === undefined ? createStaticWorkerEntrySource() : createWorkerEntrySource(input),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/*** Render the Worker module that delegates trusted API operations to the published host boundary. */
|
|
12
|
+
function createWorkerEntrySource(input) {
|
|
13
|
+
const operations = Object.fromEntries(input.operations.map((operation) => [operation, operation]));
|
|
14
|
+
return `import { createNeonServerCallerAuthenticationPort } from '@ankhorage/auth-neon';
|
|
15
|
+
import { createNeonPostgresRequestBudget } from '@ankhorage/db-postgres';
|
|
16
|
+
import { createTrustedZefixWorkerEntry } from '@ankhorage/projects/worker';
|
|
17
|
+
|
|
18
|
+
// Server-only: bundled to dist/worker/index.js, never into the public ${WORKER_WEB_DIRECTORY} assets.
|
|
19
|
+
// DATABASE_URL, ZEFIX_CREDENTIALS and ANKH_AUTH_ALLOWED_SUBJECTS are Worker secret bindings;
|
|
20
|
+
// NEON_AUTH_BASE_URL and NEON_AUTH_JWKS_URL are bound from the provisioned Neon Auth outputs.
|
|
21
|
+
export default createTrustedZefixWorkerEntry({
|
|
22
|
+
appId: ${JSON.stringify(input.appId)},
|
|
23
|
+
projectId: ${JSON.stringify(input.projectId)},
|
|
24
|
+
environment: ${JSON.stringify(input.environment)},
|
|
25
|
+
operations: ${JSON.stringify(operations)},
|
|
26
|
+
createCallerAuthentication: (env) =>
|
|
27
|
+
createNeonServerCallerAuthenticationPort({
|
|
28
|
+
authUrl: env.NEON_AUTH_BASE_URL ?? '',
|
|
29
|
+
...(env.NEON_AUTH_JWKS_URL === undefined ? {} : { jwksUrl: env.NEON_AUTH_JWKS_URL }),
|
|
30
|
+
}),
|
|
31
|
+
createRequestBudget: (env) =>
|
|
32
|
+
createNeonPostgresRequestBudget({
|
|
33
|
+
connectionString: env.DATABASE_URL ?? '',
|
|
34
|
+
limit: ${WORKER_REQUEST_LIMIT},
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
`;
|
|
38
|
+
}
|
|
39
|
+
/*** Render the Worker module for an application without server APIs: every Worker-routed request is unknown. */
|
|
40
|
+
function createStaticWorkerEntrySource() {
|
|
41
|
+
return `// Server-only: bundled to dist/worker/index.js, never into the public ${WORKER_WEB_DIRECTORY} assets.
|
|
42
|
+
// This application declares no server API, so the Worker serves none.
|
|
43
|
+
export default {
|
|
44
|
+
fetch: (): Response =>
|
|
45
|
+
Response.json({ error: { code: 'not_found' } }, { status: 404, headers: { 'cache-control': 'no-store' } }),
|
|
46
|
+
};
|
|
47
|
+
`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Built Worker module uploaded by the Workers adapter; server code never lives in the asset directory. */
|
|
2
|
+
export declare const WORKER_ENTRY_SOURCE_PATH = "src/worker/index.ts";
|
|
3
|
+
/** Built Worker module consumed by the Workers deployment boundary. */
|
|
4
|
+
export declare const WORKER_BUILT_ENTRY = "dist/worker/index.js";
|
|
5
|
+
/** Public static assets uploaded beside the Worker. */
|
|
6
|
+
export declare const WORKER_WEB_DIRECTORY = "dist/web";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Built Worker module uploaded by the Workers adapter; server code never lives in the asset directory. */
|
|
2
|
+
export const WORKER_ENTRY_SOURCE_PATH = 'src/worker/index.ts';
|
|
3
|
+
/** Built Worker module consumed by the Workers deployment boundary. */
|
|
4
|
+
export const WORKER_BUILT_ENTRY = 'dist/worker/index.js';
|
|
5
|
+
/** Public static assets uploaded beside the Worker. */
|
|
6
|
+
export const WORKER_WEB_DIRECTORY = 'dist/web';
|
package/dist/index.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export { createTrustedSocialManagerFileSystemPersistenceAsync, type TrustedSocia
|
|
|
18
18
|
export { createTrustedSocialManagerHost, createTrustedSocialManagerHostAsync, type CreateTrustedSocialManagerHostAsyncInput, type CreateTrustedSocialManagerHostInput, } from './features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js';
|
|
19
19
|
export { createTrustedSocialManagerLocalServerAsync, type CreateTrustedSocialManagerLocalServerAsyncInput, findTrustedSocialManagerApiDefinition, type TrustedSocialManagerLocalServer, } from './features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js';
|
|
20
20
|
export { createTrustedZefixHost, type CreateTrustedZefixHostInput, type TrustedZefixHost, } from './features/trusted-zefix-host/composition/createTrustedZefixHost.js';
|
|
21
|
+
export { createTrustedZefixWorkerEntry, type CreateTrustedZefixWorkerEntryInput, type TrustedZefixWorkerCallerAuthentication, type TrustedZefixWorkerEntry, type TrustedZefixWorkerEnvironment, type TrustedZefixWorkerRequestBudget, } from './features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js';
|
|
22
|
+
export { createTrustedZefixWorkerHandler, type CreateTrustedZefixWorkerHandlerInput, type TrustedZefixWorkerCredentials, type TrustedZefixWorkerFetch, } from './features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js';
|
|
21
23
|
export type { CreateProjectInput, MaterializeProjectRevisionInput, Project, ProjectManifest, ProjectManifestDraft, ProjectManifestRevision, ReloadProjectManifestInput, SaveProjectManifestInput, UpdateProjectInput, } from './types/projects.js';
|
|
22
24
|
export type { SocialManagerCaller, SocialManagerDestination, SocialManagerDraft, SocialManagerDraftContent, SocialManagerDraftStore, SocialManagerDraftUpdate, SocialManagerMedia, SocialManagerMediaStore, SocialManagerMediaUpload, SocialManagerScope, } from './types/socialManager.js';
|
|
23
25
|
export type { SocialManagerPublicationBinding, SocialManagerPublicationDependencies, SocialManagerPublicationRequest, } from './types/socialManagerPublication.js';
|
package/dist/index.js
CHANGED
|
@@ -17,3 +17,5 @@ export { createTrustedSocialManagerFileSystemPersistenceAsync, } from './feature
|
|
|
17
17
|
export { createTrustedSocialManagerHost, createTrustedSocialManagerHostAsync, } from './features/trusted-social-manager-host/composition/createTrustedSocialManagerHost.js';
|
|
18
18
|
export { createTrustedSocialManagerLocalServerAsync, findTrustedSocialManagerApiDefinition, } from './features/trusted-social-manager-host/composition/createTrustedSocialManagerLocalServerAsync.js';
|
|
19
19
|
export { createTrustedZefixHost, } from './features/trusted-zefix-host/composition/createTrustedZefixHost.js';
|
|
20
|
+
export { createTrustedZefixWorkerEntry, } from './features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js';
|
|
21
|
+
export { createTrustedZefixWorkerHandler, } from './features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Worker-safe entrypoint: only Fetch-standard trusted host composition, no filesystem or Node APIs. */
|
|
2
|
+
export { createTrustedZefixWorkerEntry, type CreateTrustedZefixWorkerEntryInput, type TrustedZefixWorkerCallerAuthentication, type TrustedZefixWorkerEntry, type TrustedZefixWorkerEnvironment, type TrustedZefixWorkerRequestBudget, } from '../features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js';
|
|
3
|
+
export { createTrustedZefixWorkerHandler, type CreateTrustedZefixWorkerHandlerInput, type TrustedZefixWorkerCredentials, type TrustedZefixWorkerFetch, } from '../features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js';
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Worker-safe entrypoint: only Fetch-standard trusted host composition, no filesystem or Node APIs. */
|
|
2
|
+
export { createTrustedZefixWorkerEntry, } from '../features/trusted-zefix-host/composition/createTrustedZefixWorkerEntry.js';
|
|
3
|
+
export { createTrustedZefixWorkerHandler, } from '../features/trusted-zefix-host/composition/createTrustedZefixWorkerHandler.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ankhorage/projects",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "Standalone project identity and repository actions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ankhorage",
|
|
@@ -32,6 +32,10 @@
|
|
|
32
32
|
"types": "./dist/index.d.ts",
|
|
33
33
|
"import": "./dist/index.js"
|
|
34
34
|
},
|
|
35
|
+
"./worker": {
|
|
36
|
+
"types": "./dist/worker/index.d.ts",
|
|
37
|
+
"import": "./dist/worker/index.js"
|
|
38
|
+
},
|
|
35
39
|
"./capabilities": {
|
|
36
40
|
"types": "./dist/capabilities/index.d.ts",
|
|
37
41
|
"import": "./dist/capabilities/index.js"
|
|
@@ -54,26 +58,26 @@
|
|
|
54
58
|
"version-packages": "ankhorage-changeset version"
|
|
55
59
|
},
|
|
56
60
|
"devDependencies": {
|
|
57
|
-
"@ankhorage/devtools": "^2.12.
|
|
61
|
+
"@ankhorage/devtools": "^2.12.19",
|
|
58
62
|
"@ankhorage/paradox": "^0.6.2",
|
|
59
63
|
"@types/bun": "^1.4.5",
|
|
60
64
|
"@types/node": "^26.6.11",
|
|
61
65
|
"typescript": "~6.0.3"
|
|
62
66
|
},
|
|
63
67
|
"dependencies": {
|
|
64
|
-
"@ankhorage/api": "^0.
|
|
68
|
+
"@ankhorage/api": "^0.8.0",
|
|
65
69
|
"@ankhorage/api-fastify": "^0.4.0",
|
|
66
70
|
"@ankhorage/connection": "^0.3.0",
|
|
67
|
-
"@ankhorage/contracts": "^
|
|
71
|
+
"@ankhorage/contracts": "^28.0.0",
|
|
68
72
|
"@ankhorage/data-sources": "^2.4.0",
|
|
69
|
-
"@ankhorage/expo-runtime": "^7.
|
|
73
|
+
"@ankhorage/expo-runtime": "^7.10.0",
|
|
70
74
|
"@ankhorage/flow": "^0.12.0",
|
|
71
|
-
"@ankhorage/navigator": "^3.
|
|
75
|
+
"@ankhorage/navigator": "^3.9.0",
|
|
72
76
|
"@ankhorage/permissions": "^0.2.64",
|
|
73
|
-
"@ankhorage/runtime": "^5.
|
|
77
|
+
"@ankhorage/runtime": "^5.8.1",
|
|
74
78
|
"@ankhorage/secrets": "^0.3.2",
|
|
75
79
|
"@ankhorage/social": "^0.7.0",
|
|
76
|
-
"@ankhorage/templates": "^12.
|
|
80
|
+
"@ankhorage/templates": "^12.8.0",
|
|
77
81
|
"@ankhorage/utility": "^1.11.0"
|
|
78
82
|
},
|
|
79
83
|
"ankh": {
|