@runeditrun/rer 0.2.80 → 0.2.82
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 +12 -0
- package/cli/deploy-needs.mjs +4 -2
- package/cli/export.mjs +1 -1
- package/cli/ledger-refusal.mjs +18 -0
- package/cli/portability-migrations.mjs +30 -11
- package/cli/portability-worker.mjs +3 -1
- package/cli/portability.mjs +2 -0
- package/cli/release.mjs +4 -4
- package/cli/site-hosting.mjs +90 -0
- package/cli/site-render.mjs +3 -2
- package/cli/site.mjs +5 -2
- package/edition-authoring/base-copies.mjs +12 -1
- package/edition-authoring/copy-checkout.mjs +152 -1
- package/edition-authoring/files.mjs +1 -1
- package/edition-authoring/runtime-dependencies.mjs +108 -0
- package/global/CHANGELOG.md +25 -0
- package/global/README.md +12 -0
- package/modules/demo/README.md +8 -0
- package/modules/demo/navigation.mjs +131 -15
- package/modules/dependencies/auth.mjs +2 -2
- package/modules/deploy-kit/owner.mjs +8 -1
- package/modules/import-kit/src/d1/apply-effects.ts +33 -0
- package/modules/import-kit/src/d1/apply.ts +38 -10
- package/modules/import-kit/src/door/ADOPTING.md +452 -0
- package/modules/import-kit/src/door/README.md +553 -0
- package/modules/import-kit/src/door/admission.ts +45 -0
- package/modules/import-kit/src/door/archive.ts +129 -0
- package/modules/import-kit/src/door/authority.ts +107 -0
- package/modules/import-kit/src/door/failures.ts +70 -0
- package/modules/import-kit/src/door/grants.ts +162 -0
- package/modules/import-kit/src/door/handler.ts +90 -0
- package/modules/import-kit/src/door/index.ts +20 -0
- package/modules/import-kit/src/door/intake/csv.ts +74 -0
- package/modules/import-kit/src/door/intake/json.ts +182 -0
- package/modules/import-kit/src/door/intake/projection.ts +61 -0
- package/modules/import-kit/src/door/intake/types.ts +28 -0
- package/modules/import-kit/src/door/intake-policy.ts +38 -0
- package/modules/import-kit/src/door/intake-upload.ts +91 -0
- package/modules/import-kit/src/door/inventory.ts +68 -0
- package/modules/import-kit/src/door/jobs.ts +134 -0
- package/modules/import-kit/src/door/limits.ts +16 -0
- package/modules/import-kit/src/door/operator.ts +41 -0
- package/modules/import-kit/src/door/planning.ts +227 -0
- package/modules/import-kit/src/door/protocol.ts +38 -0
- package/modules/import-kit/src/door/refusals.ts +51 -0
- package/modules/import-kit/src/door/schema.ts +101 -0
- package/modules/import-kit/src/door/store.ts +152 -0
- package/modules/import-kit/src/door/types.ts +100 -0
- package/modules/import-kit/src/door/uploads.ts +98 -0
- package/modules/import-kit/src/provenance/numeric-credentials.ts +40 -0
- package/modules/import-kit/src/readers/README.md +139 -0
- package/modules/import-kit/src/readers/api-policy.ts +67 -0
- package/modules/import-kit/src/readers/api.ts +86 -0
- package/modules/import-kit/src/readers/bytes.ts +73 -0
- package/modules/import-kit/src/readers/errors.ts +33 -0
- package/modules/import-kit/src/readers/file.ts +74 -0
- package/modules/import-kit/src/readers/index.ts +3 -0
- package/modules/import-kit/src/readers/json.ts +29 -0
- package/modules/import-kit/src/readers/numeric-lexemes.ts +104 -0
- package/modules/import-kit/src/readers/original.ts +31 -0
- package/modules/import-kit/src/readers/records.ts +105 -0
- package/modules/import-kit/src/types.ts +3 -1
- package/modules/operator-auth/README.md +92 -3
- package/modules/operator-auth/accounts/admin.mjs +52 -20
- package/modules/operator-auth/accounts/audit.mjs +24 -0
- package/modules/operator-auth/accounts/business-team.mjs +91 -0
- package/modules/operator-auth/accounts/domain-audit.mjs +24 -0
- package/modules/operator-auth/accounts/native.mjs +3 -1
- package/modules/operator-auth/accounts/settings-page.mjs +15 -2
- package/modules/operator-auth/accounts/status.mjs +7 -2
- package/modules/operator-auth/accounts/store.mjs +32 -6
- package/modules/operator-auth/business-settings.mjs +40 -0
- package/modules/operator-auth/identity/email-link/index.mjs +1 -1
- package/modules/operator-auth/identity/oidc/admin-audit.mjs +31 -0
- package/modules/operator-auth/identity/oidc/index.mjs +12 -5
- package/modules/operator-auth/identity/oidc/store.mjs +2 -0
- package/modules/operator-auth/index.d.mts +40 -1
- package/modules/operator-auth/routes.mjs +11 -6
- package/modules/operator-auth/service.mjs +8 -3
- package/modules/operator-auth/signin/index.mjs +1 -1
- package/modules/portability/README.md +82 -1
- package/modules/portability/export.mjs +6 -4
- package/modules/portability/format.mjs +5 -0
- package/modules/portability/index.d.mts +10 -2
- package/modules/portability/index.mjs +3 -2
- package/modules/portability/ledgers.mjs +27 -4
- package/modules/release/README.md +74 -2
- package/modules/release/sign.mjs +4 -2
- package/modules/release/signature.mjs +14 -7
- package/modules/release/signing-cli.mjs +2 -1
- package/modules/release/statement.mjs +2 -2
- package/modules/release/vectors/generate.mjs +1 -0
- package/modules/release/vectors/publisher-projects.mjs +133 -0
- package/modules/release/vectors/release-signature-vectors.json +5195 -0
- package/modules/release/verify.mjs +5 -1
- package/onboarding/schema/SETUP.schema.json +43 -1
- package/onboarding/schema/business-field-inputs.mjs +0 -1
- package/onboarding/schema/setup-validation.mjs +3 -0
- package/package.json +3 -2
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Keep partial and single-file runtime copies closed over their relative imports.
|
|
2
|
+
// Both maintained exporters already ship the whole foundation/runtime directory;
|
|
3
|
+
// refresh must also recover siblings omitted by an older seed's copy selection.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
const runtime = 'foundation/runtime/';
|
|
7
|
+
const code = /\.(?:[cm]?[jt]s|[jt]sx)$/;
|
|
8
|
+
const inside = (name, prefix) => name === prefix || name.startsWith(prefix + '/');
|
|
9
|
+
const mapped = (name, from, to) => to + name.slice(from.length);
|
|
10
|
+
|
|
11
|
+
// Tokenize enough module syntax to ignore comments and quoted page/CSS content.
|
|
12
|
+
// Static imports (including type imports), re-exports and literal import() /
|
|
13
|
+
// require() calls share the same relative resolution below. Templates are page
|
|
14
|
+
// content, never static module declarations.
|
|
15
|
+
export function specifiers(source) {
|
|
16
|
+
const tokens = [...source.matchAll(/\/\/[^\n]*|\/\*[\s\S]*?\*\/|`(?:\\[\s\S]|[^`\\])*`|'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*"|[\w$]+|[^\s]/g)]
|
|
17
|
+
.map(match => match[0]).filter(token => !token.startsWith('//') && !token.startsWith('/*') && !token.startsWith('`'));
|
|
18
|
+
const result = [];
|
|
19
|
+
const literal = token => /^['"]\.{1,2}\//.test(token || '') ? token.slice(1, -1) : null;
|
|
20
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
21
|
+
if (!['import', 'export', 'require'].includes(tokens[i])) continue;
|
|
22
|
+
if (tokens[i - 1] === '.' || (tokens[i] === 'require' && tokens[i + 1] !== '(')) continue;
|
|
23
|
+
if (tokens[i] === 'export' && !['{', '*', 'type'].includes(tokens[i + 1])) continue;
|
|
24
|
+
let value = literal(tokens[i + 1]);
|
|
25
|
+
if (tokens[i + 1] === '(') value = literal(tokens[i + 2]);
|
|
26
|
+
else if (!value) {
|
|
27
|
+
for (let j = i + 1; j < tokens.length && ![';', 'import', 'export'].includes(tokens[j]); j++) {
|
|
28
|
+
if (tokens[j] === 'from') { value = literal(tokens[j + 1]); break; }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (value) result.push(value);
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function resolve(tree, source, specifier) {
|
|
37
|
+
const name = path.posix.normalize(path.posix.join(path.posix.dirname(source), specifier));
|
|
38
|
+
const candidates = [name];
|
|
39
|
+
// TypeScript source commonly uses its emitted JS extension in imports.
|
|
40
|
+
const replacement = {'.js': ['.ts', '.tsx', '.d.ts'], '.mjs': ['.mts', '.d.mts'], '.cjs': ['.cts', '.d.cts']}[path.posix.extname(name)];
|
|
41
|
+
if (replacement) candidates.push(...replacement.map(extension => name.slice(0, -path.posix.extname(name).length) + extension));
|
|
42
|
+
if (!path.posix.extname(name)) {
|
|
43
|
+
for (const suffix of ['.ts', '.tsx', '.mts', '.mjs', '.js', '.jsx', '.cts', '.cjs', '.json']) candidates.push(name + suffix, name + '/index' + suffix);
|
|
44
|
+
}
|
|
45
|
+
const found = candidates.find(candidate => tree.has(candidate));
|
|
46
|
+
if (!found || !found.startsWith(runtime)) throw Error(`Cannot ship runtime dependency ${specifier} from ${source}; keep its source inside foundation/runtime`);
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function completeRuntimeCopies(plans, {tree, read, local, upstream, revision, checkTarget}) {
|
|
51
|
+
const queue = plans.flatMap(plan => plan.sources.filter(([source]) => source.startsWith(runtime) && code.test(source))
|
|
52
|
+
.map(([source]) => ({source, target: mapped(source, plan.copy.originPath, plan.copy.path), baseline: plan.copy.revision})));
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
const blobs = new Map();
|
|
55
|
+
function bytes(source) {
|
|
56
|
+
const object = tree.get(source).object;
|
|
57
|
+
if (!blobs.has(object)) blobs.set(object, read.blobs([object]).get(object));
|
|
58
|
+
return blobs.get(object).toString('utf8');
|
|
59
|
+
}
|
|
60
|
+
function include(source, target, baseline) {
|
|
61
|
+
checkTarget(target);
|
|
62
|
+
let plan = plans.find(plan => inside(target, plan.copy.path));
|
|
63
|
+
if (plan && mapped(target, plan.copy.path, plan.copy.originPath) !== source) throw Error(`Runtime dependency ${target} conflicts with its Base copy mapping`);
|
|
64
|
+
// A missing recorded file is a removal, not an omitted sibling. Restoring
|
|
65
|
+
// it here would bypass refresh's retirement/removal plan and could leave
|
|
66
|
+
// the recreated source outside its record. Refuse before any writes.
|
|
67
|
+
if (plan?.removed.includes(target)) throw Error(`Runtime dependency ${target} was removed locally but is still imported; no files were refreshed. Restore it or adapt the importing module before refreshing.`);
|
|
68
|
+
if (plan?.copy.adapted?.[target]) {
|
|
69
|
+
queue.push({source, target, baseline});
|
|
70
|
+
return; // Keep seed bytes while supplying the shipped module's dependencies.
|
|
71
|
+
}
|
|
72
|
+
if (!plan?.sources.some(([name]) => name === source)) {
|
|
73
|
+
const actual = local(target);
|
|
74
|
+
const previous = actual && read.tree(baseline).get(source);
|
|
75
|
+
const previousDigest = previous && read.digests([previous.object]).get(previous.object);
|
|
76
|
+
if (actual && actual !== upstream.get(tree.get(source).object) && actual !== previousDigest) {
|
|
77
|
+
// Existing unrecorded siblings belong to the seed, just as in the
|
|
78
|
+
// ordinary copy selection. They already satisfy this import's presence;
|
|
79
|
+
// only an absent sibling needs to be supplied by Base. Keep traversing
|
|
80
|
+
// the shipped graph so a later adoption cannot omit its dependencies.
|
|
81
|
+
// Recorded edits and acknowledgements were checked before planning.
|
|
82
|
+
queue.push({source, target, baseline});
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (!plan) {
|
|
86
|
+
if (plans.some(plan => inside(plan.copy.path, target))) throw Error(`Runtime dependency ${target} overlaps an existing Base copy`);
|
|
87
|
+
plan = {copy: {path: target, originPath: source, revision, files: {}, modes: {}}, sources: [], removed: []};
|
|
88
|
+
plans.push(plan);
|
|
89
|
+
}
|
|
90
|
+
plan.sources.push([source, tree.get(source)]);
|
|
91
|
+
plan.removed = plan.removed.filter(name => name !== target);
|
|
92
|
+
}
|
|
93
|
+
queue.push({source, target, baseline});
|
|
94
|
+
}
|
|
95
|
+
for (let i = 0; i < queue.length; i++) {
|
|
96
|
+
const {source, target, baseline} = queue[i];
|
|
97
|
+
const key = source + '\0' + target;
|
|
98
|
+
if (seen.has(key)) continue;
|
|
99
|
+
seen.add(key);
|
|
100
|
+
if (code.test(source)) for (const specifier of specifiers(bytes(source))) {
|
|
101
|
+
const dependency = resolve(tree, source, specifier);
|
|
102
|
+
include(dependency, path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency)), baseline);
|
|
103
|
+
}
|
|
104
|
+
// JS type imports also need the declaration file used by edition typechecks.
|
|
105
|
+
const declaration = source.replace(/\.mjs$/, '.d.mts').replace(/\.cjs$/, '.d.cts');
|
|
106
|
+
if (declaration !== source && tree.has(declaration)) include(declaration, target.replace(/\.mjs$/, '.d.mts').replace(/\.cjs$/, '.d.cts'), baseline);
|
|
107
|
+
}
|
|
108
|
+
}
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.82
|
|
4
|
+
|
|
5
|
+
- Deliver the accepted import-door intake implementation and its runtime and type dependencies at `@runeditrun/rer/modules/import-kit/door`, preserving the D1 entry.
|
|
6
|
+
- Close relative imports from every recorded authoring module, including mirror-origin copies and acknowledged local adaptations, and record newly delivered siblings. Preserve tracked unrecorded siblings without traversing them.
|
|
7
|
+
- Preflight destination types, casing, ownership and effective permissions using filesystem metadata and access checks before writes, accounting for the plan's own removals; overwrites require writable files (and ownership when setting copy modes), while creates and removals require writable, searchable directories. Refuse untracked authoring helper collisions, including ignored files or matching Base bytes. Races, disk and I/O failures, new-directory umasks and two new case-distinct names on an insensitive volume remain outside these checks.
|
|
8
|
+
- Check the packed door lifecycle and refresh pinned Pegboard, Pencil, Dial, Placemat and Envelope checkouts before package publication, resolving every direct authoring module's relative imports, running local and package verification and requiring byte-identical records on repeat.
|
|
9
|
+
- To adopt with a copied authoring CLI predating 0.2.82, update the installed package and run `rer refresh-base --ref FULL_40_HEX_COMMIT --base /absolute/base-checkout` through that package.
|
|
10
|
+
|
|
11
|
+
### Known issues
|
|
12
|
+
|
|
13
|
+
- For a Base-equal untracked, ignored or excluded authoring helper, the suggested `git add -f` followed by refresh can leave `verify-base` reporting `unrecordedCopies`; from the seed root, run `node node_modules/@runeditrun/rer/edition-authoring/cli.mjs record-base LOCAL_PATH ORIGIN_PATH FULL_40_HEX_COMMIT --base /absolute/base-checkout`, then the same entry's `verify-base --base /absolute/base-checkout`. Corrected refusal text ships in 0.2.83.
|
|
14
|
+
- On case-insensitive APFS, the suggested `mv -i` for a Base-equal committed `Copy-Checkout.mjs` can leave the old Git index spelling, so refresh succeeds but verification fails; move its `.refresh-backup` outside the checkout, run `git rm --cached -- PATH/Copy-Checkout.mjs` and `git add -- PATH/copy-checkout.mjs base-copies.json`, then verify again. This preserves both the backup and delivered bytes; corrected refusal text ships in 0.2.83.
|
|
15
|
+
|
|
16
|
+
## 0.2.81
|
|
17
|
+
|
|
18
|
+
- Import RER Platform archives into native installations by migration hash, recording `rer_migrations` as the source ledger without restoring it as product data; expose `mapMigrationLedger` for custom archive adapters and name unapplied files in preflight refusals.
|
|
19
|
+
- Project declared import intake fields before storing chunks, keeping excluded values such as Auth0 password hashes and Okta credentials and factors out of custody.
|
|
20
|
+
- Validate preserving import adapters before every apply batch, including resumed work; retain earlier admitted batches for Undo when later preparation is refused.
|
|
21
|
+
- Deliver the shared three-way Run chooser and hosting guide through Base refresh, with byte-exact Copy, listing-aware Assisted and Managed links, and commands that wrap under adopted seed themes.
|
|
22
|
+
- Keep demo Run exits within available header space and reveal the full accessible link on keyboard focus without moving host controls.
|
|
23
|
+
- Add transactional audit hooks for native operator administration and direct installation exports; audit provider unlink only for a new pin generation.
|
|
24
|
+
- Apply signed runtime Business settings, same-origin logos, app accents, local overrides and owner-scoped team reconciliation; allow owners to stop settings with fresh sign-in proof.
|
|
25
|
+
- Authorize explicit publisher project lists with version 2 signing anchors and an optional signing publisher, while retaining version 1 verification.
|
|
26
|
+
- Simplify the shared Run invocation, show the public Roadmap without repository citations, and preserve retained runtime dependencies during Base copy refresh.
|
|
27
|
+
|
|
3
28
|
## 0.2.80
|
|
4
29
|
|
|
5
30
|
- Healthy doctor now exits 0 when local settings are present.
|
package/global/README.md
CHANGED
|
@@ -337,6 +337,7 @@ line that still names it. A later refresh is a version bump:
|
|
|
337
337
|
| `@runeditrun/rer/modules/deploy-kit/owner`, `/owner-cli`, `/prepare`, `/provider` | deploy kit | `scripts/base-cli/modules/deploy-kit/*.mjs` |
|
|
338
338
|
| `@runeditrun/rer/modules/operator-auth`, `/dev`, `/dev-admission`, `/accounts/native`, `/identity/email-link` | operator auth | `scripts/base-cli/modules/operator-auth/index.mjs`, `dev/index.mjs`, `dev-admission.mjs`, `accounts/native.mjs`, `identity/email-link/index.mjs` |
|
|
339
339
|
| `@runeditrun/rer/modules/import-kit/d1` | asynchronous D1 import, reviewed reversal-policy conversion and preserved-undo preview (TypeScript Worker entry) | `scripts/base-cli/modules/import-kit/src/d1/index.ts` |
|
|
340
|
+
| `@runeditrun/rer/modules/import-kit/door` | reviewed operator and grant intake, plan, apply, reconciliation and Undo (TypeScript Worker entry) | `scripts/base-cli/modules/import-kit/src/door/index.ts` |
|
|
340
341
|
| `@runeditrun/rer/modules/erasure/fence` | erasure fence statements | `scripts/base-cli/modules/erasure/fence.mjs` |
|
|
341
342
|
| `@runeditrun/rer/modules/owner-claim`, `/modules/dependencies` | owner claim, dependency links | `scripts/base-cli/modules/owner-claim/index.mjs`, `dependencies/index.mjs` |
|
|
342
343
|
| `@runeditrun/rer/internal/PATH` | any other package file, for tests | `scripts/base-cli/PATH`, and `scripts/base-onboarding/PATH` with PATH under `onboarding/` |
|
|
@@ -611,3 +612,14 @@ setup process is still running, `confirm-no-turn-started JOB_ID
|
|
|
611
612
|
checkout changed or the provider recorded a session for it. It reads the
|
|
612
613
|
checkout with Git inside the same boundary, because setup could have changed
|
|
613
614
|
the checkout's Git configuration.
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
## Import door for adopting Workers
|
|
618
|
+
|
|
619
|
+
Bundle `@runeditrun/rer/modules/import-kit/door` to use the maintained
|
|
620
|
+
`createImportOperatorHandler` or `createImportDoorHandler`, schema migrations,
|
|
621
|
+
settings hooks and public option types. This TypeScript entry includes its real
|
|
622
|
+
runtime and type dependencies. The existing
|
|
623
|
+
`@runeditrun/rer/modules/import-kit/d1` entry remains available. See the
|
|
624
|
+
[adoption guide](https://github.com/runeditrun/base/blob/main/modules/import-kit/src/door/ADOPTING.md)
|
|
625
|
+
for native adapters, consent, declared intake projection and reviewed apply/Undo.
|
package/modules/demo/README.md
CHANGED
|
@@ -37,6 +37,14 @@ Production build/deploy refuses that setting; ordinary builds keep real effects.
|
|
|
37
37
|
local and hosted demos. No per-seed link is required. CSS adds the label suffix without
|
|
38
38
|
changing the application's hydrated text; CSP allows exact hashes only.
|
|
39
39
|
|
|
40
|
+
The exit uses only spare space beside or directly below the label and truncates its own text.
|
|
41
|
+
It stays out of the host layout, preserving sibling rectangles and document
|
|
42
|
+
width relative to the same header with the Demo suffix but no exit. It never
|
|
43
|
+
repairs an already overflowing host header. With no readable room it remains
|
|
44
|
+
a keyboard stop; keyboard focus reveals the full link above clipping ancestors.
|
|
45
|
+
The full name is also its accessible name and title. The host keeps ownership
|
|
46
|
+
of its responsive layout.
|
|
47
|
+
|
|
40
48
|
Public sockets, WebSockets and event streams remain usable for checks. The
|
|
41
49
|
local sockets guard and hosted egress retain a small direct mail/SMS denylist;
|
|
42
50
|
use the effect helper for such sends. Hosted demos keep their isolated
|
|
@@ -1,32 +1,148 @@
|
|
|
1
|
-
// Runs after
|
|
2
|
-
//
|
|
1
|
+
// Runs after hydration and follows client navigation. Exits are out of flow:
|
|
2
|
+
// even a zero-width flex item would add a host gap and move its siblings.
|
|
3
3
|
export const NAVIGATION_SCRIPT = `(() => {
|
|
4
4
|
const settings = document.querySelector('style[data-rer-label]');
|
|
5
5
|
if (!settings.dataset.rerRun) return;
|
|
6
|
+
const exits = new Map();
|
|
7
|
+
let pending = false;
|
|
8
|
+
const set = (element, values) => {
|
|
9
|
+
for (const [key, value] of Object.entries(values)) {
|
|
10
|
+
if (element.style[key] !== value) element.style[key] = value;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
const place = (link, x, y) => {
|
|
14
|
+
const parent = link.offsetParent;
|
|
15
|
+
if (!parent || (parent === document.body && getComputedStyle(parent).position === 'static')) {
|
|
16
|
+
set(link, { left: x + scrollX + 'px', top: y + scrollY + 'px' });
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const box = parent.getBoundingClientRect();
|
|
20
|
+
const scaleX = box.width / parent.offsetWidth || 1;
|
|
21
|
+
const scaleY = box.height / parent.offsetHeight || 1;
|
|
22
|
+
set(link, {
|
|
23
|
+
left: ((x - box.left) / scaleX - parent.clientLeft + parent.scrollLeft) + 'px',
|
|
24
|
+
top: ((y - box.top) / scaleY - parent.clientTop + parent.scrollTop) + 'px'
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
const fit = (position, link) => {
|
|
28
|
+
if (link.matches(':popover-open')) return;
|
|
29
|
+
const box = position.getBoundingClientRect();
|
|
30
|
+
if (!position.getClientRects().length || !box.width || !box.height) {
|
|
31
|
+
set(link, { display: 'none' });
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
set(link, { display: 'block' });
|
|
35
|
+
const parent = position.parentElement;
|
|
36
|
+
const layout = getComputedStyle(parent);
|
|
37
|
+
const bounds = parent.getBoundingClientRect();
|
|
38
|
+
const rtl = layout.direction === 'rtl';
|
|
39
|
+
const height = parseFloat(getComputedStyle(link).lineHeight);
|
|
40
|
+
let top = box.top + (box.height - height) / 2;
|
|
41
|
+
// Clip only our own allocation to the viewport and any clipping ancestors.
|
|
42
|
+
let left = Math.max(0, bounds.left + parseFloat(layout.paddingLeft));
|
|
43
|
+
let right = Math.min(document.documentElement.clientWidth, bounds.right - parseFloat(layout.paddingRight));
|
|
44
|
+
let bottom = bounds.bottom - parseFloat(layout.paddingBottom);
|
|
45
|
+
for (let ancestor = parent; ancestor; ancestor = ancestor.parentElement) {
|
|
46
|
+
const style = getComputedStyle(ancestor);
|
|
47
|
+
if (style.overflowX !== 'visible') {
|
|
48
|
+
const clip = ancestor.getBoundingClientRect();
|
|
49
|
+
left = Math.max(left, clip.left + ancestor.clientLeft);
|
|
50
|
+
right = Math.min(right, clip.left + ancestor.clientLeft + ancestor.clientWidth);
|
|
51
|
+
bottom = Math.min(bottom, clip.top + ancestor.clientTop + ancestor.clientHeight);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
left = Math.min(document.documentElement.clientWidth, left);
|
|
55
|
+
right = Math.max(left, right);
|
|
56
|
+
const start = rtl ? box.left : box.right;
|
|
57
|
+
const siblings = [...parent.children].filter(sibling => sibling !== position && !sibling.hasAttribute('data-rer-demo-exit'));
|
|
58
|
+
const outerLeft = left, outerRight = right;
|
|
59
|
+
for (const sibling of siblings) {
|
|
60
|
+
const rect = sibling.getBoundingClientRect();
|
|
61
|
+
if (!rect.width || rect.bottom <= top || rect.top >= top + height) continue;
|
|
62
|
+
if (rtl && rect.left < start) left = Math.max(left, Math.min(start, rect.right));
|
|
63
|
+
if (!rtl && rect.right > start) right = Math.min(right, Math.max(start, rect.left));
|
|
64
|
+
}
|
|
65
|
+
const range = document.createRange();
|
|
66
|
+
range.selectNodeContents(link.firstElementChild);
|
|
67
|
+
const natural = range.getBoundingClientRect().width;
|
|
68
|
+
const gap = parseFloat(getComputedStyle(link).fontSize) / 2;
|
|
69
|
+
const room = Math.max(0, (rtl ? start - left : right - start) - 2 * gap);
|
|
70
|
+
let width = Math.min(natural, room);
|
|
71
|
+
let x = Math.max(left, Math.min(right, rtl ? start - gap - width : start + gap));
|
|
72
|
+
// A vertical rail may already have an empty row under the lockup. Use it
|
|
73
|
+
// only if the whole exit fits there without touching any existing item.
|
|
74
|
+
const below = box.bottom + gap;
|
|
75
|
+
const belowX = rtl ? box.right - gap - natural : box.left + gap;
|
|
76
|
+
if (width < natural && below + height <= bottom && belowX >= outerLeft && belowX + natural <= outerRight && siblings.every(sibling => {
|
|
77
|
+
const rect = sibling.getBoundingClientRect();
|
|
78
|
+
return !rect.width || rect.bottom <= below || rect.top >= below + height || rect.right <= belowX || rect.left >= belowX + natural;
|
|
79
|
+
})) { width = natural; x = belowX; top = below; }
|
|
80
|
+
// With no readable room, retain a keyboard stop, revealed in the top layer
|
|
81
|
+
// on focus. Neither its box nor its focus ring can extend the document.
|
|
82
|
+
const concealed = width < height;
|
|
83
|
+
set(link, { width: (concealed ? 0 : width) + 'px', height: height + 'px', clipPath: concealed ? 'inset(50%)' : 'none' });
|
|
84
|
+
place(link, x, top);
|
|
85
|
+
};
|
|
86
|
+
const schedule = () => {
|
|
87
|
+
if (pending) return;
|
|
88
|
+
pending = true;
|
|
89
|
+
requestAnimationFrame(() => { pending = false; update(); });
|
|
90
|
+
};
|
|
91
|
+
const sizes = new ResizeObserver(schedule);
|
|
6
92
|
const update = () => {
|
|
93
|
+
for (const [position, link] of exits) {
|
|
94
|
+
if (!position.isConnected || link.previousElementSibling !== position) {
|
|
95
|
+
link.remove();
|
|
96
|
+
exits.delete(position);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
7
99
|
for (const label of document.querySelectorAll('[data-rer-name]')) {
|
|
8
100
|
const position = label.closest('a,button') ?? label;
|
|
9
|
-
if (
|
|
101
|
+
if (exits.has(position)) continue;
|
|
10
102
|
const link = document.createElement('a');
|
|
11
103
|
link.setAttribute('data-rer-demo-exit', '');
|
|
104
|
+
link.setAttribute('popover', 'manual');
|
|
12
105
|
link.href = settings.dataset.rerRun;
|
|
13
|
-
link.
|
|
106
|
+
link.title = link.ariaLabel = 'Run ' + settings.dataset.rerProduct;
|
|
107
|
+
const text = document.createElement('span');
|
|
108
|
+
text.textContent = link.title;
|
|
109
|
+
link.append(text);
|
|
110
|
+
// Own only the exit's box, including when a host styles all nav anchors.
|
|
111
|
+
set(link, { position: 'absolute', display: 'block', boxSizing: 'border-box', margin: '0', padding: '0', border: '0', minWidth: '0', maxWidth: 'none', inset: 'auto', width: '0', overflow: 'visible', background: 'transparent' });
|
|
112
|
+
link.addEventListener('focus', () => {
|
|
113
|
+
if (!link.matches(':focus-visible')) return;
|
|
114
|
+
link.showPopover();
|
|
115
|
+
const box = position.getBoundingClientRect();
|
|
116
|
+
set(link, { position: 'fixed', clipPath: 'none', width: 'max-content', maxWidth: 'calc(100vw - 16px)', height: 'auto', padding: '6px', background: 'Canvas', color: 'CanvasText' });
|
|
117
|
+
const rect = link.getBoundingClientRect();
|
|
118
|
+
set(link, { left: Math.max(8, Math.min(box.left, innerWidth - rect.width - 8)) + 'px', top: Math.max(8, Math.min(box.bottom + 4, innerHeight - rect.height - 8)) + 'px' });
|
|
119
|
+
});
|
|
120
|
+
link.addEventListener('blur', () => {
|
|
121
|
+
if (!link.matches(':popover-open')) return;
|
|
122
|
+
link.hidePopover();
|
|
123
|
+
set(link, { position: 'absolute', maxWidth: 'none', padding: '0', background: 'transparent', color: '' });
|
|
124
|
+
schedule();
|
|
125
|
+
});
|
|
14
126
|
position.after(link);
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
link.style.textAlign = 'center';
|
|
20
|
-
link.style.marginInlineStart = '0';
|
|
21
|
-
}
|
|
127
|
+
exits.set(position, link);
|
|
128
|
+
sizes.observe(position);
|
|
129
|
+
sizes.observe(position.parentElement);
|
|
130
|
+
for (const sibling of position.parentElement.children) if (sibling !== link) sizes.observe(sibling);
|
|
22
131
|
}
|
|
132
|
+
for (const [position, link] of exits) fit(position, link);
|
|
23
133
|
};
|
|
24
134
|
const start = () => {
|
|
25
135
|
update();
|
|
26
|
-
new MutationObserver(
|
|
136
|
+
new MutationObserver(records => {
|
|
137
|
+
if (records.some(record => !record.target.closest?.('[data-rer-demo-exit]'))) schedule();
|
|
138
|
+
}).observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
|
|
139
|
+
addEventListener('resize', schedule);
|
|
140
|
+
addEventListener('scroll', schedule, true);
|
|
141
|
+
document.fonts.addEventListener('loadingdone', schedule);
|
|
27
142
|
};
|
|
28
|
-
const ready = () =>
|
|
143
|
+
const ready = () => requestAnimationFrame(() => requestAnimationFrame(start));
|
|
29
144
|
if (document.readyState === 'complete') ready();
|
|
30
|
-
else
|
|
145
|
+
else addEventListener('load', ready, { once: true });
|
|
31
146
|
})()`;
|
|
32
|
-
|
|
147
|
+
|
|
148
|
+
export const NAVIGATION_STYLE = '[data-rer-demo-exit]{color:var(--rer-link,inherit);font:inherit;font-size:.8125rem;font-weight:400;line-height:1.5;white-space:nowrap;text-decoration:underline;text-underline-offset:3px}[data-rer-demo-exit]>span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}[data-rer-demo-exit]:focus-visible{outline:2px solid var(--rer-focus,currentColor);outline-offset:-2px}';
|
|
@@ -35,7 +35,7 @@ export function linkedProviders(options) {
|
|
|
35
35
|
async links(){const p=await current();const links=[...await staticProviders?.links()??[],...(p!==staticProviders?await p?.links()??[]:[])];return [...new Map(links.map(link=>[link.id,link])).values()];},
|
|
36
36
|
// The Auth dependency is linked and unlinked through its own approval routes;
|
|
37
37
|
// a static provider keeps its own pin controls.
|
|
38
|
-
async relink(id){if(id==='auth')throw new Error('Use the dependency link with fresh local owner proof');return staticProviders.relink(id);},
|
|
39
|
-
async unlink(id){if(id==='auth')throw new Error('Use the dependency unlink with fresh local owner proof');return staticProviders.unlink(id);},
|
|
38
|
+
async relink(id, audit){if(id==='auth')throw new Error('Use the dependency link with fresh local owner proof');return staticProviders.relink(id, audit);},
|
|
39
|
+
async unlink(id, audit){if(id==='auth')throw new Error('Use the dependency unlink with fresh local owner proof');return staticProviders.unlink(id, audit);},
|
|
40
40
|
};
|
|
41
41
|
}
|
|
@@ -28,6 +28,13 @@ const ENTRY_KEYS = {d1:['binding'],r2:['binding','locationHint'],kv:['binding'],
|
|
|
28
28
|
|
|
29
29
|
export function refuse(code, kind, name) { const error = new Error(code); error.resource = `${kind}:${name}`; return error; }
|
|
30
30
|
|
|
31
|
+
/** Where a declaration deploys: `platforms` when it lists them, else Workers alone. */
|
|
32
|
+
export function ownerPlatforms(declaration) {
|
|
33
|
+
const platforms = declaration.platforms ?? ['workers'];
|
|
34
|
+
assert(Array.isArray(platforms) && platforms.length > 0 && new Set(platforms).size === platforms.length && platforms.every(item => ['workers','container'].includes(item)), 'invalid-platforms');
|
|
35
|
+
return platforms;
|
|
36
|
+
}
|
|
37
|
+
|
|
31
38
|
export function ownerWorkerName(project, environment) {
|
|
32
39
|
assert(typeof project === 'string' && /^(?:[a-z0-9][a-z0-9-]*\/)?[a-z0-9-]+$/.test(project) && segment.test(project.split('/').at(-1)), 'invalid-owner-project');
|
|
33
40
|
assert(typeof environment === 'string' && environment.length <= 32 && segment.test(environment), 'invalid-owner-environment');
|
|
@@ -116,7 +123,7 @@ export function localOnlyBinding(declaration, localOnlyKeys = []) {
|
|
|
116
123
|
export function ownerPlan(target, declaration, artifact, { localOnlyKeys = [], env = {} } = {}) {
|
|
117
124
|
assert(declaration?.version === 1 && typeof declaration === 'object' && Object.keys(declaration).every(key => DECLARATION_KEYS.includes(key)), 'invalid-owner-declaration');
|
|
118
125
|
assert(declaration.publicSettings === undefined || Array.isArray(declaration.publicSettings) && new Set(declaration.publicSettings).size === declaration.publicSettings.length && declaration.publicSettings.every(name => typeof name === 'string' && /^[A-Z][A-Z0-9_]*$/.test(name)), 'invalid-public-settings');
|
|
119
|
-
|
|
126
|
+
ownerPlatforms(declaration);
|
|
120
127
|
if (declaration.container !== undefined) {
|
|
121
128
|
const config=declaration.container;
|
|
122
129
|
assert(config&&typeof config==='object'&&!Array.isArray(config)&&Object.keys(config).every(key=>['engine','cacheContract','runner','hostVariables','ingress'].includes(key))&&['node','workerd'].includes(config.engine),'invalid-container');
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ImportJob, PlanEntry, ProvenanceRow, TargetRow } from '../types.ts';
|
|
2
|
+
import type { D1ImportContext } from './types.ts';
|
|
3
|
+
import type { D1UndoEffect } from './undo-types.ts';
|
|
4
|
+
import { canonicalJson, sha256, attachmentHash } from '../provenance/identity.ts';
|
|
5
|
+
import { effectIdentity } from '../storage/provenance.ts';
|
|
6
|
+
import { remaining } from './budget.ts';
|
|
7
|
+
|
|
8
|
+
/** The exact prospective publication shape, shared by apply and admission. */
|
|
9
|
+
export function prospectiveEffect(id: string, entry: PlanEntry, index: number, before: TargetRow | undefined, destination: string): D1UndoEffect {
|
|
10
|
+
const effect = entry.effects[index], appliedRevision = sha256(canonicalJson([id, entry.identity, index, 'applied']));
|
|
11
|
+
const expected: TargetRow = { destination, targetKind: effect.targetKind, targetId: effect.targetId, value: effect.value, revision: appliedRevision, ...(effect.attachment ? { attachment: effect.attachment } : {}) };
|
|
12
|
+
const provenance: ProvenanceRow = { id: effectIdentity(id, entry.identity, index), jobId: id, sourceIdentity: entry.identity, sourceKind: entry.source.kind, sourceId: entry.source.sourceId, sourceHash: entry.source.payloadHash, artifactHash: entry.source.artifactHash, location: entry.source.location, destination, targetKind: effect.targetKind, targetId: effect.targetId, valueHash: sha256(canonicalJson(effect.value)), attachmentHash: attachmentHash(effect.attachment), appliedRevision, before: before ?? null, reversed: false };
|
|
13
|
+
return { provenance, expected, retained: false };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Small-batch callers can admit consecutive pending effects together, before
|
|
17
|
+
* any of them publish. This avoids repeatedly listing the growing native set
|
|
18
|
+
* for each one-record publication. Admission never survives a public request. */
|
|
19
|
+
export async function admissionWindow(job: ImportJob, entries: PlanEntry[], effects: D1UndoEffect[], plan: { entries: PlanEntry[] }, context: D1ImportContext, batches: number, batchSize: number, publicationCost: number): Promise<void> {
|
|
20
|
+
let end = job.checkpoint + entries.length;
|
|
21
|
+
const limit = Math.min(job.total, job.checkpoint + batchSize * Math.min(batches, Math.ceil(20 / batchSize)));
|
|
22
|
+
for (const entry of plan.entries.slice(end, limit)) {
|
|
23
|
+
if (effects.length + entry.effects.length > 1000 || remaining(context) - publicationCost < 40 + entry.effects.length * 16) break;
|
|
24
|
+
const { database, targets } = context.storage;
|
|
25
|
+
if (!await database.prepare('SELECT 1 AS present FROM ik_sources WHERE identity=?').bind(entry.identity).first()) {
|
|
26
|
+
for (const [index, effect] of entry.effects.entries()) {
|
|
27
|
+
const before = await targets.read(database, context.destination, effect.targetKind, effect.targetId);
|
|
28
|
+
effects.push(prospectiveEffect(job.id, entry, index, before, context.destination));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
end++;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -2,12 +2,14 @@ import { retainedSql } from './retained-values.ts';
|
|
|
2
2
|
import { nativeStagingScope, readStagedTarget, expectedStagedTarget, type NativeStagingScope } from './native-staging-context.ts';
|
|
3
3
|
import { targetGuards } from './target-guards.ts';
|
|
4
4
|
import { D1RequestLimitError, requestContext, remaining } from './budget.ts';
|
|
5
|
-
import type { ImportJob, PlanEntry
|
|
5
|
+
import type { ImportJob, PlanEntry } from '../types.ts';
|
|
6
6
|
import { canonicalJson, sha256, attachmentHash } from '../provenance/identity.ts';
|
|
7
7
|
import { validateEffect } from '../plan/index.ts';
|
|
8
|
-
import {
|
|
8
|
+
import { prospectiveEffect, admissionWindow } from './apply-effects.ts';
|
|
9
9
|
import type { D1ImportContext, D1Sql } from './types.ts';
|
|
10
|
-
import {
|
|
10
|
+
import type { D1UndoEffect } from './undo-types.ts';
|
|
11
|
+
import { reversalState } from './undo-state.ts';
|
|
12
|
+
import { atomic, atomicCount, atomicPrefix, authorize, guard, limits, sql, fitsBatch, readAtomic } from './database.ts';
|
|
11
13
|
import { stored, boundary, storedReads } from './jobs.ts';
|
|
12
14
|
import { custodyGuards, validatedProvenance, inventoryGuards, reusedSourceGuards } from './integrity.ts';
|
|
13
15
|
import { supersedeTarget } from './history.ts';
|
|
@@ -19,6 +21,8 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
|
|
|
19
21
|
const id = typeof jobOrId === 'string' ? jobOrId : jobOrId.id, { batchSize, maxBatches } = limits(context);
|
|
20
22
|
await authorize(context, 'apply');
|
|
21
23
|
let current = await stored(id, context, 'apply'), published: ImportJob | undefined;
|
|
24
|
+
const admitted = new Map<string, string>();
|
|
25
|
+
let preparing = context.storage.targets.preparePreservedUndo;
|
|
22
26
|
try {
|
|
23
27
|
for (let count = 0; count < maxBatches; count++) {
|
|
24
28
|
const { job, plan } = current;
|
|
@@ -27,6 +31,7 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
|
|
|
27
31
|
if (job.state === 'completed') { await atomic(context, 'apply', [...boundary(job, plan, 'apply'), ...custodyGuards(plan, id), ...await inventoryGuards(job, plan, context)], 0, nativeStagingScope(job, plan)); return job; }
|
|
28
32
|
if (!['queued', 'applying', 'failed'].includes(job.state)) throw new Error('IMPORT_ALREADY_REVERSING');
|
|
29
33
|
const statements: D1Sql[] = [...boundary(job, plan, 'apply'), ...custodyGuards(plan, id), ...await inventoryGuards(job, plan, context)], entries: PlanEntry[] = [], returnReads = storedReads(job);
|
|
34
|
+
const undoEffects: D1UndoEffect[] | undefined = reversalState(job).policy === 'preserve-conflicts' ? [] : undefined;
|
|
30
35
|
let effects = 0, scope = nativeStagingScope(job, plan);
|
|
31
36
|
let prefix = atomicPrefix(context, 'apply', statements, scope);
|
|
32
37
|
let planned = prefix ? prefix.count(progress(job, 0), returnReads) : cost(context, publication(job, 0, statements, scope), returnReads);
|
|
@@ -38,21 +43,44 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
|
|
|
38
43
|
const reserve = 40 + entry.effects.length * 16;
|
|
39
44
|
if (remaining(context) - planned < reserve) { if (!entries.length) { if (count > 0) return job; throw new D1RequestLimitError(); } break; }
|
|
40
45
|
const candidate: D1Sql[] = [], nextScope = { ...scope, nativeGuards:[...scope.nativeGuards], postGuards:[...scope.postGuards], targets:[...scope.targets] };
|
|
41
|
-
|
|
46
|
+
const candidateUndo: D1UndoEffect[] | undefined = undoEffects && [];
|
|
47
|
+
await publishEntry(id, entry, job.checkpoint + entries.length, context, candidate, nextScope, candidateUndo);
|
|
42
48
|
const nextPrefix = prefix?.extend(candidate);
|
|
43
49
|
const next = nextPrefix ? undefined : publication(job, entries.length + 1, [...statements, ...candidate], nextScope);
|
|
44
50
|
const spent = nextPrefix ? nextPrefix.count(progress(job, entries.length + 1), returnReads) : cost(context, next!, returnReads);
|
|
45
51
|
if (spent > remaining(context)) { if (entries.length) break; if (count > 0) return job; throw new D1RequestLimitError(); }
|
|
46
52
|
const fits = nextPrefix ? true : fitsBatch(context, 'apply', next!.statements, next!.scope);
|
|
47
53
|
if (!fits && entries.length) break;
|
|
48
|
-
statements.push(...candidate); prefix = nextPrefix;
|
|
54
|
+
statements.push(...candidate); undoEffects?.push(...candidateUndo!); prefix = nextPrefix;
|
|
49
55
|
scope = nextScope; entries.push(entry); effects += entry.effects.length; planned = spent;
|
|
50
56
|
if (!fits) break;
|
|
51
57
|
}
|
|
58
|
+
// Check the preserving contract before every native publication, including
|
|
59
|
+
// batches resumed from a nonzero checkpoint.
|
|
60
|
+
// This read-only admission makes no undo decision and authorizes no
|
|
61
|
+
// effects. Apply still fences its own exact before-images atomically.
|
|
62
|
+
// Do not copy this potentially large native snapshot into staging's
|
|
63
|
+
// compact baseline, which must fit every private publication batch.
|
|
64
|
+
if (undoEffects && (!admitted.size || undoEffects.some(effect => admitted.get(effect.provenance.id) !== sha256(canonicalJson(effect))) || preparing !== context.storage.targets.preparePreservedUndo)) {
|
|
65
|
+
const { classifyUndo } = await import('./undo-snapshot.ts');
|
|
66
|
+
const { database, targets } = context.storage;
|
|
67
|
+
const prepare = targets.preparePreservedUndo;
|
|
68
|
+
if (typeof prepare !== 'function') throw new Error('IMPORT_PRESERVED_UNDO_ADAPTER_REQUIRED');
|
|
69
|
+
await admissionWindow(job, entries, undoEffects, plan, context, maxBatches - count, batchSize, planned);
|
|
70
|
+
const snapshot = await prepare.call(targets, database, context.destination, structuredClone(undoEffects));
|
|
71
|
+
const admission = classifyUndo(undoEffects, snapshot, context);
|
|
72
|
+
await readAtomic(context, admission.guards, nativeStagingScope(job, plan), 'apply');
|
|
73
|
+
admitted.clear();
|
|
74
|
+
for (const effect of undoEffects) admitted.set(effect.provenance.id, sha256(canonicalJson(effect)));
|
|
75
|
+
preparing = prepare;
|
|
76
|
+
}
|
|
77
|
+
if (undoEffects && preparing !== context.storage.targets.preparePreservedUndo) throw new Error('IMPORT_PRESERVED_UNDO_ADAPTER_REQUIRED');
|
|
52
78
|
const request = publication(job, entries.length, statements, scope), done = job.checkpoint + entries.length === job.total;
|
|
53
79
|
await atomic(context, 'apply', request.statements, returnReads, request.scope);
|
|
54
80
|
current = await stored(id, context, 'apply'); published = current.job;
|
|
55
|
-
|
|
81
|
+
// Preserving admission spends a variable number of reads; let the exact
|
|
82
|
+
// next-batch budget check decide whether more work fits.
|
|
83
|
+
if (done || (!undoEffects && remaining(context) < 200)) return published;
|
|
56
84
|
}
|
|
57
85
|
} catch (error) {
|
|
58
86
|
// Later preflight has no native effects. Its measured budget exhaustion
|
|
@@ -62,7 +90,7 @@ export async function applyD1ImportBatches(jobOrId: ImportJob | string, context:
|
|
|
62
90
|
}
|
|
63
91
|
return current.job;
|
|
64
92
|
}
|
|
65
|
-
async function publishEntry(id: string, entry: PlanEntry, ordinal: number, context: D1ImportContext, statements: D1Sql[], scope: NativeStagingScope): Promise<void> {
|
|
93
|
+
async function publishEntry(id: string, entry: PlanEntry, ordinal: number, context: D1ImportContext, statements: D1Sql[], scope: NativeStagingScope, undoEffects?: D1UndoEffect[]): Promise<void> {
|
|
66
94
|
const { database: db, targets } = context.storage, effectsHash = sha256(canonicalJson(entry.effects));
|
|
67
95
|
const prior = await db.prepare('SELECT * FROM ik_sources WHERE identity=?').bind(entry.identity).first();
|
|
68
96
|
if (prior) {
|
|
@@ -87,12 +115,12 @@ async function publishEntry(id: string, entry: PlanEntry, ordinal: number, conte
|
|
|
87
115
|
validateEffect(effect);
|
|
88
116
|
const before = await readStagedTarget(context, scope, effect.targetKind, effect.targetId);
|
|
89
117
|
if (before ? effect.expectedRevision !== before.revision : effect.expectedRevision !== undefined) throw new Error('TARGET_REVISION_CONFLICT');
|
|
90
|
-
const
|
|
91
|
-
const
|
|
118
|
+
const prospective = prospectiveEffect(id, entry, index, before, context.destination);
|
|
119
|
+
const { expected: row, provenance: p } = prospective;
|
|
92
120
|
expectedStagedTarget(scope,effect.targetKind,effect.targetId,true);
|
|
93
121
|
const post = targetGuards(targets, row, context.destination, effect.targetKind, effect.targetId);
|
|
94
122
|
scope.postGuards.push(...post);
|
|
95
|
-
|
|
123
|
+
undoEffects?.push(prospective);
|
|
96
124
|
await supersedeTarget(p, before, context, statements);
|
|
97
125
|
const record_json=canonicalJson(p);
|
|
98
126
|
statements.push(...targetGuards(targets,before ?? null, context.destination, effect.targetKind, effect.targetId), ...targets.write(row), ...post, changed(retainedSql(['INSERT INTO ik_provenance(id,job_id,ordinal,effect_ordinal,source_identity,destination,target_kind,target_id,record_json) VALUES(', ',', ',', ',', ',', ',', ',', ',', ',', ')'], [p.id, id, ordinal, index, entry.identity, context.destination, effect.targetKind, effect.targetId, record_json], [8]),putRow('ik_provenance',{id:p.id,job_id:id,ordinal,effect_ordinal:index,source_identity:entry.identity,destination:context.destination,target_kind:effect.targetKind,target_id:effect.targetId,reversed:0,record_json})));
|